当前位置: 首页 > news >正文

【java】springboot注解关键字

springboot注解关键字

  • @Value
  • @Service
  • @Repository
  • @Configuration
  • @Controller
  • @Component

@Value

@Value 是 Spring Boot 中用于注入外部配置的注解,它允许你将配置文件(如 application.properties 或 application.yml)中的值注入到 Bean 的字段、方法参数或构造函数参数中。这个注解是实现外部化配置的核心工具之一,有助于将代码与配置解耦。

@Service
public class MyService {@Value("${app.name}")private String appName;  // 从配置文件中读取 app.name 的值@Value("${server.port}")private int serverPort;  // 自动转换为 int 类型// 使用默认值(如果配置文件中未定义)@Value("${app.timeout:3000}")private long timeout;  // 如果 app.timeout 未定义,则使用 3000
}

@Service

在 Spring Boot 中,@Service 是一个重要的注解,它用于标记一个类作为业务逻辑层(Service Layer)的组件。这个注解是 Spring 框架的核心注解之一,属于 @Component 的特殊化形式,用于表示该类是一个服务组件。
核心作用
声明组件:告诉 Spring 这个类是一个服务组件,应该被自动扫描并注册为 Spring Bean。
业务逻辑封装:作为业务逻辑层,处理业务规则、事务管理、数据处理等核心功能。
依赖注入:允许其他组件(如 Controller)通过依赖注入使用该服务。

package com.example.productplatform.service;import com.example.productplatform.entity.Product;
import com.example.productplatform.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Service  // 声明为服务组件
@Transactional  // 开启事务管理(可选)
public class ProductService {private final ProductRepository productRepository;@Autowired  // 构造函数注入(推荐)public ProductService(ProductRepository productRepository) {this.productRepository = productRepository;}// 业务逻辑方法public List<Product> getAllProducts() {return productRepository.findAll();}public Product getProductById(Long id) {return productRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Product not found"));}public Product saveProduct(Product product) {return productRepository.save(product);}public void deleteProduct(Long id) {productRepository.deleteById(id);}
}

@Repository

在 Spring Boot 中,@Repository 是一个关键注解,用于标记数据访问层(DAO,Data Access Object)的组件。它是 Spring 框架的核心注解之一,属于 @Component 的特殊化形式,专门用于数据库访问类。
核心作用
声明组件:告诉 Spring 这个类是一个数据访问组件,应被自动扫描并注册为 Spring Bean。
数据访问封装:作为数据访问层,处理与数据库的交互(如查询、插入、更新等)。
异常转换:自动将特定的数据库异常(如 SQL 异常)转换为 Spring 的 DataAccessException 体系,提供更统一的异常处理。

package com.example.productplatform.repository;import com.example.productplatform.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import java.util.List;@Repository  // 声明为数据访问组件
public interface ProductRepository extends JpaRepository<Product, Long> {// Spring Data JPA 会自动实现基本的 CRUD 方法// 自定义查询方法(根据方法名自动生成 SQL)List<Product> findByNameContaining(String name);// 使用 @Query 注解定义复杂查询@Query("SELECT p FROM Product p WHERE p.price > :minPrice")List<Product> findByPriceGreaterThan(double minPrice);
}

配合 @Query注解,实现复杂查询。
注解原理
@Repository 是 @Component 的派生注解,具有相同的功能。
Spring 会在启动时扫描带有 @Repository 的类,并将它们注册为单例 Bean。
当使用 Spring Data JPA 时,接口会被自动代理实现,无需手动编写实现类。

@Configuration

在 Spring Boot 中,@Configuration 是一个核心注解,用于定义配置类。它允许你使用 Java 代码替代传统的 XML 配置文件,通过 Bean 方法来定义和组织应用组件。这个注解是 Spring 框架中基于 Java 的配置方式的基础。
核心作用
声明配置类:告诉 Spring 这个类是一个配置类,类似于 XML 中的 标签。
定义 Bean:通过 @Bean 注解在方法上定义应用所需的组件。
管理 Bean 依赖:在配置类中可以注入其他 Bean,定义它们之间的依赖关系。
支持组件扫描:通常与 @ComponentScan 配合,自动发现和注册组件。

package com.example.productplatform.config;import com.example.productplatform.service.MyService;
import com.example.productplatform.service.MyServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration  // 声明为配置类
public class AppConfig {@Bean  // 定义一个 Beanpublic MyService myService() {return new MyServiceImpl();  // 返回 Bean 实例}@Beanpublic AnotherBean anotherBean() {// Bean 方法可以依赖其他 Beanreturn new AnotherBean(myService());}
}

@Controller

在 Spring Boot 中,@Controller 是一个核心注解,用于标记一个类作为 Web 控制器组件。它是 Spring MVC 框架的基础,负责处理 HTTP 请求并返回响应,是客户端与服务端交互的入口点。
核心作用
声明控制器:告诉 Spring 这个类是一个控制器组件,应被自动扫描并注册为 Spring Bean。
处理 HTTP 请求:通过 @RequestMapping 或其派生注解(如 @GetMapping、@PostMapping)映射 HTTP 请求到具体方法。
请求参数解析:自动解析请求参数、路径变量、请求体等数据。
视图渲染或 RESTful 响应:支持返回视图名称(用于页面渲染)或直接返回数据(RESTful API)。

package com.example.productplatform.controller;import com.example.productplatform.entity.Product;
import com.example.productplatform.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;@Controller  // 声明为控制器
@RequestMapping("/products")  // 根路径
public class ProductController {private final ProductService productService;@Autowired  // 构造函数注入public ProductController(ProductService productService) {this.productService = productService;}// 处理 GET 请求:/products@GetMappingpublic String listProducts(Model model) {model.addAttribute("products", productService.getAllProducts());return "product-list";  // 返回视图名称}// 处理 GET 请求:/products/{id}@GetMapping("/{id}")public String getProduct(@PathVariable Long id, Model model) {model.addAttribute("product", productService.getProductById(id));return "product-detail";  // 返回视图名称}// 处理 POST 请求:/products@PostMappingpublic String addProduct(@ModelAttribute Product product) {productService.saveProduct(product);return "redirect:/products";  // 重定向}
}

注解原理
@Controller 是 @Component 的派生注解,具有相同的功能。
Spring 会在启动时扫描带有 @Controller 的类,并将它们注册为单例 Bean。
控制器中的方法通过 @RequestMapping 或其派生注解映射到 HTTP 请求路径。

@Component

在 Spring Boot 中,@Component 是一个基础注解,用于标记一个类作为 Spring 容器管理的组件。它是所有组件注解(如 @Service、@Repository、@Controller)的父注解,主要用于自动扫描和注册 Bean。
核心作用
声明组件:告诉 Spring 这个类是一个组件,应被自动扫描并注册为 Spring Bean。
组件扫描:配合 @ComponentScan 或 @SpringBootApplication(默认包含 @ComponentScan),Spring 会自动发现并注册所有带有 @Component 或其派生注解的类。
依赖注入:允许其他组件通过依赖注入使用该组件。

package com.example.productplatform.component;import org.springframework.stereotype.Component;@Component  // 声明为 Spring 组件
public class MyComponent {public String doSomething() {return "Component is working!";}
}

最佳实践
组件单一职责:每个组件专注于特定功能。
避免过度使用:优先使用 @Service、@Repository、@Controller 等语义化注解,仅在没有更合适的注解时使用 @Component。
组件扫描路径:确保组件位于 @ComponentScan 指定的包路径下(默认是主应用类所在包及其子包)。
依赖注入方式:优先使用构造函数注入,提高代码可测试性。

相关文章:

  • 【MATLAB去噪算法】基于CEEMD联合小波阈值去噪算法(第三期)
  • leetcode hot100 链表(二)
  • Spring Boot + MyBatis-Plus 读写分离与多 Slave 负载均衡示例
  • 适老化场景重构:现代家政老年照护虚拟仿真实训室建设方案​
  • 如何在 vue 中实现一个自定义拖拽的指令或插件
  • qt 事件顺序
  • Laravel模型状态:深入理解Eloquent的隐秘力量
  • QT常用控件(1)
  • metersphere不同域名的参数在链路测试中如何传递?
  • 项目任务,修改svip用户的存储空间。
  • 微博app 最新版本15.5.2 mfp 分析
  • RagFlow优化代码解析(一)
  • 操作系统:生态思政
  • 现代密码学 | 椭圆曲线密码学—附py代码
  • 如何从系统日志中排查磁盘错误?
  • 0518蚂蚁暑期实习上机考试题1:数组操作
  • “轻量应用服务器” vs. “云服务器CVM”:小白入门腾讯云,哪款“云机”更适合你?(场景、配置、价格对比解析)
  • 神经符号集成-三篇综述
  • Docker 镜像(或 Docker 容器)中查找文件命令
  • 2023-2025 时序大模型相关工作汇总
  • 网站表单及商品列表详情模板/网站推广服务商
  • 中企动力做网站/青岛网站开发公司
  • 苏州广告公司招聘/优化课程
  • 大连哪里做网站/网站查询系统
  • 事业单位报名网站/上海百度移动关键词排名优化
  • 如何去掉Wordpress访问网站/营销号