Spring 中常用的注解非常丰富,涵盖了依赖注入、AOP、事务管理、Web 开发等各个方面。以下是一些常见的 Spring 注解及其作用和示例:
-
@ComponentScan:指示 Spring 在指定的包及其子包中查找被 Spring 管理的组件(如 @Component、@Service、@Repository、@Controller 等)并注册为 Bean。
@Configuration @ComponentScan(basePackages = "com.example") public class AppConfig { // 配置类 }
-
@Component:用于标识一个类作为 Spring 组件(Bean)。
@Component public class MyComponent { // 组件类 }
-
@Autowired:用于自动装配 Bean,通过类型进行匹配。
@Component public class MyService { private final MyRepository myRepository; @Autowired public MyService(MyRepository myRepository) { this.myRepository = myRepository; } }
-
@Qualifier:配合 @Autowired 使用,指定具体的 Bean 名称。
@Component public class MyService { private final MyRepository myRepository; @Autowired public MyService(@Qualifier("myRepositoryImpl") MyRepository myRepository) { this.myRepository = myRepository; } }
-
@Service:用于标识一个服务层组件。
@Service public class MyService { // 服务类 }
-
@Repository:用于标识一个数据访问层组件(DAO)。
@Repository public class MyRepositoryImpl implements MyRepository { // 数据访问类 }
-
@Controller:用于标识一个控制器类(Spring MVC)。
@Controller public class MyController { @Autowired private MyService myService; // 控制器方法 }
-
@RequestMapping:用于映射 HTTP 请求到控制器方法。
@Controller @RequestMapping("/api") public class MyController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } }
-
@ResponseBody:用于将方法返回的对象直接作为 HTTP 响应体返回。
@RestController public class MyRestController { @GetMapping("/api/data") public ResponseEntity<String> getData() { return ResponseEntity.ok("Some data"); } }
-
@Transactional:用于声明事务管理的方法或类。
@Service public class MyService { @Autowired private MyRepository myRepository; @Transactional public void performTransaction() { // 执行事务操作 } }
这些注解只是 Spring 中的一部分,还有许多其他有用的注解可用于实现各种功能和行为。注解的使用可以极大地简化 Spring 应用的开发和维护工作。