先定义一个接口,然后根据条件实例化接口的实现类。
public interface IMyBean {
void hello();
}
1.区分环境,实例化bean
public class MyBeanDev implements IMyBean{
@Override
public void hello() {
System.out.println("from dev...");
}
}
@Bean
@Profile("dev")
public IMyBean myBeanDev(){
MyBeanDev myBeanDev = new MyBeanDev();
myBeanDev.hello();
return myBeanDev;
}
2.实现condition接口,@Override matches方法,自定义生效条件
public class MyBeanMatch implements IMyBean, Condition {
@Override
public void hello() {
System.out.println("up to matches...");
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return "ok".equals(context.getEnvironment().getProperty("mybean.ok"));
}
}
3.根据自定义配置属性,@ConditionalOnProperty
@Bean
@ConditionalOnProperty(name = {"mybean.ok"}, havingValue = "ok", matchIfMissing = false)
public IMyBean myBeanOK() {
MyBeanOk myBeanOk = new MyBeanOk();
myBeanOk.hello();
return myBeanOk;
}