1) @ConditionalOnBean
功能:在IOC容器中存在指定bean时,加载当前bean
//将Teacher作为bean注入IOC
@Component
public class Teacher{
}public class Student{
}@Configuration
public class MyBeanFactory{//如果IOC容器中存在Teacher这个bean,则将student作为bean注入@ConditionalOnBean(value={Teacher.class})@BeanStudent student(){return new Student();}
}
2) @ConditionalOnMissingBean
功能:在IOC中不包含指定bean时,加载当前bean
public class Student{
}@Configuration
public class MyBeanFactory{//如果IOC容器中不存在Student,则注入Student@ConditionalOnMissingBean(value={Student.class})@BeanStudent student(){return new Student();}
}
3) @ConditionalOnClass
功能:如果当前项目包含指定类,则加载当前bean
// com.entity.Student
public class Student{
}@Configuration
public class MyBeanFactory{//如果项目中含有Student类,则加载当前bean@ConditionalOnClass(name="com.entity.student")@BeanStudent student(){return Student();}
}
4) @ConditionalOnMissingClass
功能:如果当前项目不包含指定类,则加载当前bean
public class Student{
}@Configuration
public class MyBeanFactory{//如果项目中不包含Teacher类,则加载当前bean@ConditionalOnMissingClass(name="com.entity.Teacher")@BeanStudent student(){return Student();}
}
5) @ConditionalOnProperty
功能:如果配置文件有指定属性,并且属性值与预期值一致,则注入当前bean
在配置文件配置如下属性:
*****************************
student.enable=true
***************************** @Configuration
public class MyBeanFactory{//如果配置文件中配置了student.enable,并且student.enable=true, 则加载当前bean@ConditionalOnProperty(value="student.enable" , havingValue="true" )@BeanStudent student(){return Student();}
}
6) @ConditionalOnResource
功能:如果项目中包含指定资源,则加载当前bean
// 假设有 /static/index.html
@Configuration
public class MyBeanFactory{//如果包含 /static/index.html 资源,就加载当前bean@ConditionalOnResource(resources="/static/index.html" )@BeanStudent student(){return Student();}
}
7) @ConditionalOnWebApplication 、@ConditionalOnNotWebApplication
功能:如果当前项目是web应用 ( 或不是web应用 ) 时生成当前bean
@Configuration
public class MyBeanFactory{/** 如果是web应用,则加载Student作为bean* 否则加载Teacher作为bean*/@ConditionalOnWenApplication@BeanStudent student(){return Student();}@ConditionalOnNotWebApplication@BeanTeacher teacher(){return new Teacher();}
}