Spirng常用的复杂注解
- @Configuration: 声明一个类是配置类,其中包含
@Bean
方法来定义bean。 - @Bean: 在配置类中定义一个方法返回的对象将会成为Spring容器中的一个bean。
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:hsql://localhost/xdb"); dataSource.setUsername("sa"); dataSource.setPassword(""); return dataSource; } }
【2】@ComponentScan
- @ComponentScan: 自动扫描指定包及其子包下的所有带有特定注解的类(如
@Component
,@Service
,@Repository
,@Controller
)作为Spring的bean。
@Configuration @ComponentScan(basePackages = {"com.example.service", "com.example.repository"}) public class AppConfig { }
【3】@Autowired 和 @Qualifier
@Service("specialDao") public class SpecialDao implements MyDao {} @Service("defaultDao") public class DefaultDao implements MyDao {} @Service public class MyService { private final MyDao myDao; @Autowired public MyService(@Qualifier("specialDao") MyDao myDao) { this.myDao = myDao; } }
【4】@Transactional
- @Transactional: 用于声明式事务管理。可以应用于类级别或方法级别。
@Service public class MyService { @Transactional(readOnly = true) public void readData() { // 只读操作 } @Transactional public void writeData() { // 写操作 } }
【5】@RestController 和 @RequestMapping
- @RestController: 结合了
@Controller
和@ResponseBody
,用于创建RESTful Web服务。 - @RequestMapping: 用于映射HTTP请求到处理程序方法。
@RestController @RequestMapping("/api/users") public class UserController { @GetMapping public List<User> getAllUsers() { // 获取所有用户 } @PostMapping public ResponseEntity<String> createUser(@RequestBody User user) { // 创建用户 return ResponseEntity.ok("User created successfully"); } }
【6】@RequestBody 和 @PathVariable
- @RequestBody: 用于将HTTP请求体绑定到方法参数(Json格式参数对象)。
- @PathVariable: 用于从URL路径中提取变量值。
@PostMapping("/users") public ResponseEntity<String> createUser(@RequestBody User user) { // 处理用户对象 return ResponseEntity.ok("User created successfully"); } @GetMapping("/users/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { // 根据ID获取用户 return ResponseEntity.ok(user); }
【7】@Scope
- @Scope: 用于定义bean的作用域。默认情况下,Spring bean是单例(Singleton)的。你可以使用这个注解来改变其作用域。
@Service @Scope("prototype") public class PrototypeService { // 此service每次都会创建新的实例 }
【8】@PostConstruct 和 @PreDestroy
- @PostConstruct: 用于标注在依赖注入完成后需要执行的方法。
- @PreDestroy: 用于标注在bean销毁前需要执行的方法。
@Service public class LifecycleService { @PostConstruct public void init() { System.out.println("LifecycleService initialized."); } @PreDestroy public void destroy() { System.out.println("LifecycleService destroyed."); } }
【9】@Lazy
- @Lazy: 延迟初始化bean,直到首次访问该bean为止。
@Service @Lazy public class LazyService { // 延迟初始化 }
【10】@Value 和 @Async
- @Value: 用于注入配置文件中的属性值或常量。
- @Async: 用于异步执行方法。需要在配置类中启用
@EnableAsync
。
@Service public class ConfigService { @Value("${app.name}") private String appName; @Value("10") private int someNumber; @Value("#{systemProperties['os.name']}") private String osName; } @Service @EnableAsync public class AsyncService { @Async public Future<String> doSomethingAsync() throws InterruptedException { Thread.sleep(5000); return new AsyncResult<>("Done"); } }
【11】@Conditional
是 Spring 框架中的一个核心注解,它允许你根据某些条件来决定是否创建一个 Bean。Spring 提供了多种 @Conditional
的实现,以便根据不同的条件来控制 Bean 的创建。以下是几种常见的 @Conditional
相关的注解:
注解1:@ConditionalOnClass :用途:仅在类路径中存在指定的类时才创建 Bean。 @Configuration @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } 注解2: @ConditionalOnMissingClass 用途:仅在类路径中不存在指定的类时才创建 Bean。 @Configuration @ConditionalOnMissingClass(name = "org.springframework.web.client.RestTemplate") public class NoRestTemplateConfig { @Bean public Object noRestTemplate() { return new Object(); } } 注解3:@ConditionalOnBean 用途:仅在容器中存在指定的 Bean 时才创建 Bean。 @Configuration @ConditionalOnBean(name = "customService") public class ConditionalOnBeanConfig { @Bean public AnotherService anotherService(CustomService customService) { return new AnotherService(customService); } } 注解4:@ConditionalOnMissingBean 用途:仅在容器中不存在指定的 Bean 时才创建 Bean。 @Configuration @ConditionalOnMissingBean(name = "customService") public class ConditionalOnMissingBeanConfig { @Bean public CustomService customService() { return new CustomServiceImpl(); } } 注解5:@ConditionalOnExpression 用途:根据 SpEL 表达式评估结果来决定是否创建 Bean。 @Configuration @ConditionalOnExpression("'${app.mode}' == 'development'") public class DevelopmentConfig { @Bean public DevelopmentService developmentService() { return new DevelopmentServiceImpl(); } } 注解6:@ConditionalOnProperty 用途:根据配置文件中的属性值来决定是否创建 Bean。 @Configuration @ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true") public class FeatureConfig { @Bean public FeatureService featureService() { return new FeatureServiceImpl(); } } 注解7:@ConditionalOnResource 用途:根据资源是否存在来决定是否创建 Bean。 @Configuration @ConditionalOnResource(resources = "classpath:config.properties") public class ResourceConfig { @Bean public Properties properties() { Properties props = new Properties(); props.load(getClass().getResourceAsStream("/config.properties")); return props; } } 注解8:@ConditionalOnWebApplication 用途:仅在 Web 应用环境中创建 Bean。 @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) public class WebConfig { @Bean public WebService webService() { return new WebServiceImpl(); } }
【12】@DependsOn
是 Spring 框架中的一个注解,用于指定当前 Bean 在初始化之前需要依赖的其他 Bean。通过使用这个注解,你可以确保某个 Bean 在另一个 Bean 初始化完成之后再进行初始化。
基本用法
@DependsOn
可以应用于 @Configuration
类或者 @Bean
方法上。当在一个 @Configuration
类上使用时,该类中所有 @Bean
方法定义的 Bean 都会按照指定的顺序进行初始化。当在一个 @Bean
方法上使用时,只有该方法定义的 Bean 会按照指定的顺序进行初始化。
示例一: 在 @Configuration 类上使用:在这个例子中,beanB 和 beanC 都会在 beanA 初始化完成后进行初始化。 @Configuration @DependsOn("beanA") public class ConfigClass { @Bean public MyBean beanB() { return new MyBean(); } @Bean public MyBean2 beanC() { return new MyBean2(); } } 示例二:在 @Bean 方法上使用:在这个例子中,只有 beanB 会在 beanA 初始化完成后进行初始化。 @Configuration public class ConfigClass { @Bean @DependsOn("beanA") public MyBean beanB() { return new MyBean(); } @Bean public MyBean2 beanC() { return new MyBean2(); } } 示例三:多个依赖:在这个例子中,beanC 会在 beanA 和 beanB 都初始化完成后进行初始化。 @Configuration @DependsOn({"beanA", "beanB"}) public class ConfigClass { @Bean public MyBean beanC() { return new MyBean(); } }
注意事项
-
循环依赖:虽然
@DependsOn
可以帮助你控制 Bean 的初始化顺序,但要注意避免循环依赖。如果两个 Bean 互相依赖,可能会导致初始化失败。 -
性能影响:过度使用
@DependsOn
可能会导致 Bean 初始化顺序变得复杂,从而影响应用的启动性能。因此,在设计 Bean 依赖关系时要尽量保持简单和清晰。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库