有两个组件,MyLog 和 MyAspect,Mylog 需要依赖 MyAspect
创建MyCondition类,实现Condition接口
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 判断容器中是否有myAspect的组件
return context.getBeanFactory().containsBean("myAspect");
}
}
当容器中有myAspect的组件,那么myLog才会被实例化
@Configuration
public class MainConfig {
@Bean(value = "myAspect")
public MyAspect myAspect() {
return new MyAspect();
}
@Bean
@Conditional(value = MyCondition.class)
public MyLog myLog() {
return new MyLog();
}
}