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;
        }
  • 相关阅读:
    神经网络学习之----单层感知器
    神经网络学习之----神经网络发展史
    神经网络学习之----神经网络概述
    C语言几种常见的字符串输入
    基于单链表实现集合的交集、并集、差集的运算
    关于单链表的一些基本操作
    输入20个整数存放到一个单向链表中,并顺序逆序输出
    《你的灯亮着吗》阅读笔记
    场景调研
    站立会议总结09
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14361139.html
Copyright © 2011-2022 走看看