zoukankan      html  css  js  c++  java
  • 根据系统类型选择注入bean(windows,linux注入不同的属性)

    1:需要注入的bean

    /**
     * 选择性注入bean。。根据window,linux系统注入不同的值
     */
    @Configuration
    public class Cap5Config {
    
        /*
            linux系统注入的属性
         */
        @Bean("linuxUser")
        @Conditional(LinuxCondition.class)
        public User linuxUser() {
            return new User("linuxUser", 26);
        }
    
        /*
            Window系统注入的属性
         */
        @Bean("windowUser")
        @Conditional(value = WindowCondition.class)     //选择性注入(需要配合@Bean注解)
        public User windowUser() {
            return new User("windowUser", 26);
        }

    2:设置注册条件

    /**
     * 针对性注册bean:判断条件使用的上下文环境
     */
    public class WindowCondition implements Condition {
    
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    
            Environment environment = context.getEnvironment();
            String window = environment.getProperty("os.name");
            if (window.contains("Win")) return true;
            return false;
    
        }
    }

    3:标记条件

    @Conditional(value = WindowCondition.class)

    4:测试

    public class ConditionApplication {
        public static void main(String[] args) {
    
            AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Cap5Config.class);
    
            String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
            for (String beanName : beanDefinitionNames) {  //获取注入的所有的bean并打印
                System.out.println(beanName);
            }
        }
    }
  • 相关阅读:
    【leetcode】1030. Matrix Cells in Distance Order
    【leetcode】1031. Maximum Sum of Two Non-Overlapping Subarrays
    【leetcode】1032. Stream of Characters
    L120 单词造句
    L119
    L118
    2018.8.6邮件规范一
    L117
    L116
    L115
  • 原文地址:https://www.cnblogs.com/draymond/p/12546345.html
Copyright © 2011-2022 走看看