美文网首页
Spring 条件注解@Conditional使用

Spring 条件注解@Conditional使用

作者: 帮我的鸵鸟盖个章 | 来源:发表于2019-10-25 09:34 被阅读0次

@Conditional注解源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
    Class<? extends Condition>[] value();
}

可以知道:

  1. 该注解作用在类上或者标注在方法上

  2. 该注解需要传入一个继承Condition类的Class的集合。

Condition类源码

@FunctionalInterface
public interface Condition {
    boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}

继承Condition类需要重写matches方法,该方法返回布尔值,返回值作为@Conditional注解控制Bean的判断。

例子:以本地操作系统作为判断条件,对注入的Bean进行控制。

实现Condition类的matches方法,以操作系统进行判断,返回布尔值。

windows

/**
 * TODO
 *
 * @ClassName: WindowsCondition
 * @author: yihong
 * @since: 2019/10/24 11:52
 */
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //获取当前环境信息
        Environment environment = conditionContext.getEnvironment();
        //获得当前系统名
        String property = environment.getProperty("os.name");
        //包含Windows则说明是windows系统,返回true
        if (property.contains("Windows")) {
            return true;
        }
        return false;
    }
}

linux

/**
 * TODO
 *
 * @ClassName: LinuxCondition
 * @author: yihong
 * @since: 2019/10/24 11:58
 */
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Environment environment = conditionContext.getEnvironment();
        String property = environment.getProperty("os.name");
        if (property.contains("Linux")){
            return true;
        }
        return false;
    }
}

Bean进行注入

/**
 * TODO
 *
 * @ClassName: environmentBeanConfig
 * @author: yihong
 * @since: 2019/10/24 11:59
 */
@Configuration
public class EnvironmentBeanConfig {
    @Conditional(WindowsCondition.class)
    @Bean(name = "windows")
    public SysUser windows() {
        return new SysUser("windows");
    }

    @Conditional(LinuxCondition.class)
    @Bean(name = "linux")
    public SysUser linux() {
        return new SysUser("linux");
    }
}

打印

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(EnvironmentBeanConfig.class);
        Map<String,SysUser> userBeanMap = annotationConfigApplicationContext.getBeansOfType(SysUser.class);
        userBeanMap.forEach((k,v)->{
            System.out.println(v.getUserName());
        });
    }

结果如下:

15:06:55.444 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@574caa3f
15:06:55.462 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
15:06:55.522 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'os.name' in PropertySource 'systemProperties' with value of type String
15:06:55.524 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'os.name' in PropertySource 'systemProperties' with value of type String
15:06:55.584 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
15:06:55.586 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
15:06:55.588 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
15:06:55.588 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
15:06:55.595 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'environmentBeanConfig'
15:06:55.599 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'windows'
windows

Process finished with exit code 0

因为运行系统为windows,所以只有beanName = windows被注入了。

@Conditional标注在方法上时,控制该方法的bean注入,只能控制一个Bean

@Conditional标注在类上时,控制整个类下的Bean的注入。

Springboot还有一系列的@ConditionalOnxxx注解,均是满足一定条件就注入或者不注入。

相关文章

网友评论

      本文标题:Spring 条件注解@Conditional使用

      本文链接:https://www.haomeiwen.com/subject/vmajvctx.html