Spring的Conditional注解

Spring的Conditional注解

源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

	/**
	 * All {@link Condition Conditions} that must {@linkplain Condition#matches match}
	 * in order for the component to be registered.
	 */
	Class<? extends Condition>[] value();

}

说明

作用:
它的作用是根据条件选择注入的bean对象。
属性:
value:
用于提供一个Condition接口的实现类,实现类中需要编写具体代码实现注入的条件。
使用场景:
当我们在开发时,可能会使用多平台来测试,例如我们的测试数据库分别部署到了linux和windows两个操作系统上面,现在根据我们的工程运行环境选择连接的数据库。此时就可以使用此注解。同时基于此注解引出的@Profile注解,就是根据不同的环境,加载不同的配置信息。

示例

/**
 * @author WGR
 * @create 2020/9/16 -- 20:13
 */
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * linux系统注入的数据源
     *
     * @param lDriver
     * @param lUrl
     * @param lUsername
     * @param lPassword
     * @return
     */
    @Bean("dataSource")
    @Conditional(LinuxCondition.class)
    public DataSource createLinuxDataSource(@Value("${linux.driver}") String
                                                    lDriver,
                                            @Value("${linux.url}") String lUrl,
                                            @Value("${linux.username}") String
                                                    lUsername,
                                            @Value("${linux.password}") String
                                                    lPassword) {
        DriverManagerDataSource dataSource = new
                DriverManagerDataSource(lUrl, lUsername, lPassword);
        dataSource.setDriverClassName(lDriver);
        return dataSource;
    }

    @Bean("dataSource")
    @Conditional(WindowsCondition.class)
    public DataSource createWindowsDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

}

/**
 * @author WGR
 * @create 2020/9/16 -- 20:16
 */
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata
            metadata) {
        //获取ioc使用的beanFactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
          //获取类加载器
        ClassLoader classLoader = context.getClassLoader();
       //获取当前环境信息
        Environment environment = context.getEnvironment();
        //获取bean定义的注册类
        BeanDefinitionRegistry registry = context.getRegistry();
       //获得当前系统名
        String property = environment.getProperty("os.name");
        //包含Windows则说明是windows系统,返回true
        if (property.contains("Linux")) {
            return true;
        }
        return false;
    }
}

/**
 * @author WGR
 * @create 2020/9/16 -- 20:17
 */
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
     //获取ioc使用的beanFactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //获取类加载器
        ClassLoader classLoader = context.getClassLoader();
        //获取当前环境信息
        Environment environment = context.getEnvironment();
        /**
        * 获取所有系统环境变量
        */
        if (environment instanceof StandardEnvironment) {
            StandardEnvironment standardEnvironment = (StandardEnvironment) environment;
            Map<String, Object> map = standardEnvironment.getSystemProperties();
            for (Map.Entry<String, Object> me : map.entrySet()) {
                System.out.println(me.getKey() + "," + me.getValue());
            }
        }
       //获取bean定义的注册类
        BeanDefinitionRegistry registry = context.getRegistry();

        String[] beanDefinitionNames = registry.getBeanDefinitionNames();
        Arrays.asList(beanDefinitionNames).forEach(l ->{
            System.out.println(l);
        });
        //获得当前系统名
        String property = environment.getProperty("os.name");
        //包含Windows则说明是windows系统,返回true
        if (property.contains("Windows")) {
            return true;
        }
        return false;
    }
}


/**
 * @author WGR
 * @create 2020/9/14 -- 20:41
 */
@Configuration
@PropertySource({"jdbc.properties","linuxjdbc.properties"})
@Import(JdbcConfig.class)
public class SpirngConfigure {
}

进行测试:

public class TestSpring5 {

    public static void main(String[] args) {
        //1.获取容器
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext("com.dalianpai.spring5.conditional");
        //2.根据id获取对象
        DataSource dataSource = ac.getBean("dataSource", DataSource.class);
    }


}

posted @ 2020-09-16 21:07  天宇轩-王  阅读(210)  评论(0编辑  收藏  举报