前言
已知@Conditional注解用于指定能够注册为容器中的bean的条件。那么本篇文章将结合示例工程,从源码入手,分析@Conditional注解的如下几个方面。
- @Conditional注解的作用时机;
- Condition的执行顺序;
- 多个Condition之间的关系。
Springboot版本:2.4.1
Spring版本:5.3.2
正文
一. 示例工程搭建
示例工程结构如下所示。
Condition接口实现类如下所示。
public class MyControllerCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
System.out.println(this.getClass().getName());
return true;
}
}
public class MyDaoCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
System.out.println(this.getClass().getName());
return true;
}
}
public class MyFurtherCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
System.out.println(this.getClass().getName());
return true;
}
}
public class MyRepositoryCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
System.out.println(this.getClass().getName());
return true;
}
}
public class MyServiceCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
System.out.println(this.getClass().getName());
return true;
}
}
复制代码
业务类定义如下所示。
@Controller
@Conditional(MyControllerCondition.class)
public class MyController {}
@Conditional(MyDaoCondition.class)
public class MyDao {}
public class MyFurtherService {}
@Conditional(MyRepositoryCondition.class)
public class MyRepository {}
public class MyService {}
复制代码
配置类MyFurtherConfig定义如下。
@Configuration
@Conditional(MyFurtherCondition.class)
public class MyFurtherConfig {
@Bean
public MyFurtherService myFurtherService() {
return new MyFurtherService();
}
}
复制代码
配置类MyConfig定义如下。
@ComponentScan
@Configuration
@Import(MyDao.class)
public class MyConfig {
@Bean
@Conditional(MyServiceCondition.class)
public MyService myService() {
return new MyService();
}
@Bean