直接上代码
@Configuration public class ConditionalAutoConfig { @Bean @Conditional(RandIntCondition.class) public RandDataComponent<Integer> randIntComponent() { return new RandDataComponent<>(() -> { Random random = new Random(); return random.nextInt(1024); }); } @Bean @Conditional(RandBooleanCondition.class) public RandDataComponent<Boolean> randBooleanComponent() { return new RandDataComponent<>(() -> { Random random = new Random(); return random.nextBoolean(); }); } }
public class RandBooleanCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { String type = conditionContext.getEnvironment().getProperty("conditional.rand.type"); return "boolean".equalsIgnoreCase(type); } }
public class RandIntCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { String type = conditionContext.getEnvironment().getProperty("conditional.rand.type"); return "int".equalsIgnoreCase(type); } }
public class RandDataComponent<T> { private Supplier<T> rand; public RandDataComponent(Supplier<T> rand) { this.rand = rand; } public T rand() { return rand.get(); } }
配置文件 application.yml
conditional: rand: type : int
@Autowired private Environment environment; @RequestMapping("/hello") public String index() { // return "Hello World MXZ" + port; String type = environment.getProperty("conditional.rand.type"); return randDataComponent.rand() + " >>> " + type; }