美文网首页
spring笔记-条件注解

spring笔记-条件注解

作者: 兴浩 | 来源:发表于2019-06-01 19:24 被阅读0次

1.作用

在注入的类实例初始化加一个前置的判断条件

2.@Profile注解

@Profile注解是内置实现的一个条件注解,使用方法如下

  • 在需要注册的Bean添加@Profile注解,注解的值表示spring当前的运行环境
  • 在程序入口设置spring.profiles.active系统值为test,那么@Profile为test值的条件注解会被命中
public class ProfileTest {
    public static void main(String[] args) throws ClassNotFoundException {
        System.setProperty("spring.profiles.active","test");
        ApplicationContext context = new AnnotationConfigApplicationContext(ProfileTest.class);
System.out.println(Arrays.asList(context.getBeanNamesForType(String.class)));
    }
   
    @Bean
    @Profile("test")
    public String str1() {
        return "str1";
    }

    @Bean
    public String str3() {
        return "str3";
    }
}

结果输出:
[str1, str3]

3.@Profile注解的实现

3.1 @Profile注解的定义

这里可以看到有一个@Conditional注解,其value值ProfileCondition则是@Profile内部实现的逻辑

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

    /**
     * The set of profiles for which the annotated component should be registered.
     */
    String[] value();

}

3.2 ProfileCondition的实现

其需要实现Condition接口,实现其matches方法

class ProfileCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
        if (attrs != null) {
            for (Object value : attrs.get("value")) {
                if (context.getEnvironment().acceptsProfiles((String[]) value)) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

}

4. 自定义条件注解步骤

参照上面的逻辑,实现一个自定义注解的步骤可以总结为

相关文章