• Spring之Condition(一)


    直接上代码

      

    @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;
        }
  • 相关阅读:
    欧拉公式求四面体的体积
    欧拉公式求四面体的体积
    I
    I
    闭包传递(floyed)
    闭包传递(floyed)
    Python hypot() 函数
    Python cos() 函数
    Python atan2() 函数
    Python atan() 函数
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14361139.html
Copyright © 2020-2023  润新知