zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    JSON 串 自定义解析字段
    JspWriter与PrintWriter的关系
    Map 根据value 排序
    Log4j NDC MDC
    stray '/241' in program 错误
    【Qt开发】修改源码文件的编码格式的小技巧 .
    Tomcat 虚拟目录映射
    《疯狂Java讲义精粹》读书笔记4 基本包装类
    《疯狂Java讲义精粹》读书笔记8 不可变类
    《疯狂Java讲义精粹》读书笔记9 接口
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14361139.html
Copyright © 2011-2022 走看看