作用
必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效
扩展注解
Code
Bean1 Bean2
public class Bean1 { public Bean1() { System.out.println("我是Bean1的构造方法"); } }
public class Bean2 { public Bean2() { System.out.println("我是Bean2的构造方法"); } }
自定义比较规则
import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class ArtisanCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { //判断容器中是否有bean1的组件 if(context.getBeanFactory().containsBean("bean1")) { return true; } return false; } }
配置类
import com.tuling.testconditional.compent.Bean1; import com.tuling.testconditional.compent.Bean2; import com.tuling.testconditional.condition.ArtisanCondition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; public class MainConfig { @Bean public Bean1 bean1() { return new Bean1(); } // 如果满足ArtisanCondition中定义的规则,就实例化Bean2 @Bean @Conditional(value = ArtisanCondition.class) public Bean2 bean2() { return new Bean2(); } }
测试类
import com.tuling.testconditional.config.MainConfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MainClass { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class); for(String beanName:ctx.getBeanDefinitionNames()) { System.out.println("beanName:"+beanName); } } }
为了测试效果
重新测试
如何校验自动配置类是否生效
配置文件中增加
启用 debug=true属性;来让控制台打印自动配置报告