@Conditional与Condition接口
@Conditional来指定一定条件下注册组件对像,所有的条件必须实现org.springframework.context.annotation.Condition接口,重写matches方法,通过matches中的返回值(boolean)来决定组件是否注册。
下方案例依赖于Spring的依赖+Lombok
@Slf4j public class Test1 { @Test public void t1() { ApplicationContext ac = new AnnotationConfigApplicationContext(MainCfg.class); System.out.println("\n\n\n\n\n"); log.debug("{}", ac.getBean("person", Person.class)); log.debug("{}", ac.getBean("person1", Person.class)); } } @Configuration class MainCfg { @Bean @Conditional(CustomCondition1.class) public Person person() { return new Person(); } @Bean @Conditional(CustomCondition2.class) public Person person1() { return new Person(); } } @Data class Person { private String name; private int age; } @Slf4j class CustomCondition1 implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { log.debug("自定义condition返回true,使用该注解部分应该被加载!"); return true; } } @Slf4j class CustomCondition2 implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { log.debug("自定义condition返回false,使用该注解的部分不因该被加载!"); return false; } }