一、总结:有6个注解用来和@Bean注解一起使用来进行条件装配
@ConditionalOnBean
@ConditionalOnMissingBean
@ConditionalOnClass
@ConditionalOnMissingClass
@ConditionalOnProperty
@ConditionalOnWebApplication
@ConditionalOnExpression
各个注解的含义:
1.在容器 环境中存在指定的bean,才装配这个bean
2.在容器 环境中不存在指定的bean,才装配这个bean
3.在项目中存在指定的类,才会装配这个bean
4.在项目中不存在指定的类,才会装配这个bean
5.配置文件中存在某个属性,才会装配这个bean
6.存在某个资源,才会装配这个bean
7.打包成war包运行时,才会装配这个bean.直接idea运行或打成jar包运行则不会装配这个bean
8.如果表达式的值为真,才会装配这个bean
二、示例
1.
@Configuration
public class MyConfig {
@Bean
RestTemplate getRestTemplate(){
return new RestTemplate();
}
@Bean
@Conditional(MyCondition.class)
public Student getStudent(@Value("${tju.name}")String name,@Value("${tju.age}")int age){
return new Student(name,age);
}
@Bean
@ConditionalOnBean(name="getRestTemplate")
public Teacher getTeacher(){
return new Teacher("hi",32);
}
}
因为配置了名为getRestTemplate的bean,所以类型为Teacher的bean会被装配。如果注释掉RestTemplate bean,则Teacher bean不会被装配
@Configuration
public class MyConfig {
@Bean
@Conditional(MyCondition.class)
public Student getStudent(@Value("${tju.name}")String name,@Value("${tju.age}")int age){
return new Student(name,age);
}
@Bean
@ConditionalOnMissingBean(name="getRestTemplate")
public Teacher getTeacher(){
return new Teacher("hi",32);
}
}
因没有装配名为getRestTempalte的bean,所以Teacher类的bean会被装配;如果加上名为getRestTemplate的bean,Teacher类的bean不会被装配
@Configuration
public class MyConfig {
@Bean
@ConditionalOnClass(name={"com.example.domain.Car"})
public Teacher getTeacher(){
return new Teacher("hi",32);
}
}
如果项目中存在com.example.domain.Car这个类,则类型为Teacher的bean会被装配,否则不会被装配
@Configuration
public class MyConfig {
@Bean
@ConditionalOnMissingClass(name={"com.example.domain.Car"})
public Teacher getTeacher(){
return new Teacher("hi",32);
}
}
如果项目中不存在com.example.domain.Car这个类,则类型为Teacher的bean会被装配,否则不会被装配
@Configuration
public class MyConfig {
@Bean
@ConditionalOnProperty(prefix = "tju",name="age")
public Teacher getTeacher(){
return new Teacher("hi",32);
}
}
如果application.properties中存在tju.age这个配置属性,则类型为Teacher的bean会被装配,否则不会被装配
6.
@Configuration
public class MyConfig {
@Bean
@ConditionalOnResource(resources = {"file://d:\\0022\\0000.csv"})
public Teacher getTeacher(){
return new Teacher("hi",32);
}
}
如果文件系统存在d:\0022\0000.csv这个文件,则类型为Teacher的bean会被装配,否则不会被装配
@Configuration
public class MyConfig {
@Bean
@ConditionalOnWarDeployment
public Teacher getTeacher(){
return new Teacher("hi",44);
}
}
jar包运行不会装配类型为Teacher的bean,war包运行才会装配类型为Teacher的bean
@Configuration
public class MyConfig {
@Bean
@ConditionalOnExpression("#{'true'.equals(environment.getProperty('tju.log'))}")
public Teacher getTeacher(){
return new Teacher("hi",44);
}
}
如果application.properties中配置了属性tju.log=true,则类型为Teacher的bean会被装配,否则不会被装配