条件注解举例
@Profile 配置化条件装配
@Conditional 编程条件装配
先自定义 属性类
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnSystemPropertyCondition.class)// 用于条件判断的注解 需要实现Condition
public @interface ConditionalOnSystemProperty {// 标注了这个类会被OnSystemPropertyCondition
/**
* Java 系统属性名称
* @return
*/
String name();
/**
* Java 系统属性值
* @return
*/
String value();
}
自定义Condition
// 根据javaben中的属性进行 自定义的选择
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"));
String javaPropertyValue = System.getProperty(propertyName);
System.out.println(javaPropertyValue);
return propertyValue.equals(javaPropertyValue);
}
}
- @Profile 配置化条件装配
既然我们需要自定义 条件装配,我们就定义出一个接口
// 接口用于规定 泛型 的
public interface CalculateService {
void println();
}
子类
@Profile("Java7")
@Service
public class Java7CalculateService implements CalculateService {
@Override
public void println() {
System.out.println("Java 7 ");
}
}
@Profile("Java8")
@Service
public class Java8CalculateService implements CalculateService {
@Override
public void println() {
System.out.println("Java 8 实现");
}
}
以上就是Profile 的配置
@ComponentScan(basePackages = {"所在的包"})
public class ConditionalOnSystemPropertyBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalOnSystemPropertyBootstrap.class)
.web(WebApplicationType.NONE)
.profiles("Java8")
.run(args);
// 通过名称和类型获取 helloWorld Bean
CalculateService helloWorld = context.getBean(CalculateService.class);
helloWorld.println();
// 关闭上下文
context.close();
}
}
- Conditional配置
public class ConditionalOnSystemPropertyBootstrap {
@Bean
@ConditionalOnSystemProperty(name = “java”, value = “java”)
public String helloWorld() {
return “Hello,World yaoyonglong”;
}
public static void main(String[] args) {
ConfigurableApplicationContext context = new
SpringApplicationBuilder(ConditionalOnSystemPropertyBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);
// 通过名称和类型获取 helloWorld Bean
CalculateService helloWorld = context.getBean(“helloWorld”,String.class);
System.out.println(helloWorld );
// 关闭上下文
context.close();
}
}