@Conditional,加载匹配的Bean
进入@Conditional源码
@Conditional允许指定一个或多个Condition,当所有的Condition均匹配时,说明当前条件成立
匹配是指Condition#matches(ConditionContext,Annotated TypeMetadata)方法执行后返回true。其中方法参数ConditionContext包含Spring应用上下文相关:BeanDefinitionRegistry、ConfigurableListableBeanFactory、Environment、ResourceLoader和ClassLoader。
自定义@Conditional条件装配
public class OnSystemPropertyCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
//获取ConditionalOnSystemProperty所有的属性方法值
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
//获取ConditionalOnSystemProperty name()方法值
String ProperyName = (String) attributes.getFirst("name");
String ProperyValue = (String) attributes.getFirst("value");
//获取系统属性值
String property = System.getProperty(ProperyName);
if (Objects.equals(property,ProperyValue)) {
System.out.println("----------");
return true;
}
return false;
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {
String name();
String value();
}
@Configuration
public class ConditionalMessageConfigration {
@ConditionalOnSystemProperty(name="language",value="Chinese")
@Bean("message")
public String chineseMessage() {
return "你好,世界";
}
@ConditionalOnSystemProperty(name="language",value="English")
@Bean("message")
public String englishMessage() {
return "hello,world";
}
}
public class ConditionalOnSystemPropertyBootstrap {
public static void main(String[] args) {
System.setProperty("language","Chinese");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(ConditionalMessageConfigration.class);
context.refresh();
String message = context.getBean("message", String.class);
System.out.println(message);
}
}