【SpringBoot 】注解
参考: https://www.baeldung.com/spring-boot-annotations
@SpringBootApplication
mark the main class of a Spring Boot application:
@SpringBootApplication encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes.
@EnableAutoConfiguration
@EnableAutoConfiguration enables auto-configuration. It means that Spring Boot looks for auto-configuration beans on its classpath and automatically applies them.
we have to use this annotation with @Configuration:
@Configuration @EnableAutoConfiguration class VehicleFactoryConfig {}
条件注解
@ConditionalOnClass
当某个特定类存在于类路径时,才会被创建; 通常用于处理可选的依赖
@Configuration class Appconfig{ @Bean @ConditionalOnClass(name = "com.example.SomeClass") public MyService myService(){ return new MyServiceImpl() } }
@ConditionalOnMissingClass
当某个特定类不存在于类路径时,才会被创建; 通常用于处理可选的依赖
@Configuration
class Appconfig{
@Bean
@ConditionalOnMissingClass(name = "com.example.SomeClass")
public MyService myService(){
return new MyServiceImpl()
}
}
@ConditionalOnBean
当某个或某些特定的Bean存在于Spring容器中,当前bean才被创建;场景:一个服务需要另外一个服务作为依赖,且希望只有另外一个服务存在时,当前服务才会被创建
@Configuration class MySQLAutoconfiguration { @Bean @ConditionalOnBean(Datasource.class) public MyService myService(){ return new MyServiceImpl() } }
@ConditionalOnMissingBean
当某个或某些特定Bean不存在Spring容器中,才创建。 通常创建默认的Bean,当用户没有定义自己的Bean时
@Configuration class MySQLAutoconfiguration { @Bean @ConditionalOnBean(Datasource.class) public MyService myService(){ return new DefaultMyService() } }
@ConditionalOnProperty
@Bean @ConditionalOnProperty(name = "my.service.enabled",havingValue = "true") public MyService myService(){ return new DefaultMyService() } }
@ConditionalOnResource
某个特定的资源存在
@ConditionalOnResource(resources = "classpath:mysql.properties") Properties additionalProperties() { // ... }
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication
当应用是(或不是)一个web应用程序,bean才会创建
@ConditionalOnWebApplication HealthCheckController healthCheckController() { // ... }
@ConditionalExpression
要求:一个SPEL表达式结果=true
@Bean @ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}") DataSource dataSource() { // ... }