Conditional
@Conditional是SpringFramework的功能,SpringBoot在它的基础上定义了@ConditionalOnClass,@ConditionalOnProperty的一系列的注解来实现更丰富的内容。
自定义condition
创建ConditionalOnSystemProperty注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {
/**
* Java 系统属性名称
*
* @return
*/
String name();
/**
* Java 系统属性值
*
* @return
*/
String value();
}
创建OnSystemPropertyCondition类并且实现Condition,判断注解内的name和value是否相同,相同返回true,否则返回false
public class OnSystemPropertyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
String propertyName = String.valueOf(attributes.get("name"));
String propertyValue = String.valueOf(attributes.get("value"));
return propertyValue.equals(propertyName);
}
}
创建运行类ConditionalOnSystemPropertyBootstrap,如下
public class ConditionalOnSystemPropertyBootstrap {
@Bean
@ConditionalOnSystemProperty(name = "hello", value = "hello")
public String helloWorld() {
return "Hello,World ";
}
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalOnSystemPropertyBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);
// 通过名称和类型获取 helloWorld Bean
String helloWorld = context.getBean("helloWorld", String.class);
System.out.println("helloWorld Bean : " + helloWorld);
// 关闭上下文
context.close();
}
}
运行可以返回加载到helloWorld的bean