spring笔记-条件注解

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. 自定义条件注解步骤

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring目前的趋势是使用注解结合Java代码而不是配置来定义行为、属性、功能、规则和扩展点,因此梳理注解也是梳...
    墨雨轩夏阅读 4,902评论 0 30
  • 深入使用 Spring两种后处理器Bean 后处理器容器后处理器属性占位符配置器重写占位符配置器Spring 的自...
    渐丶忘阅读 4,824评论 0 1
  • 本来是准备看一看Spring源码的。然后在知乎上看到来一个帖子,说有一群**自己连Spring官方文档都没有完全读...
    此鱼不得水阅读 11,835评论 4 21
  • Spring致力于提供一种方法管理你的业务对象。在大量Java EE的应用中,随处可见Spring。今天我将简单的...
    JAVA架构师的圈子阅读 5,235评论 0 16
  • 7月应该是学子们最喜欢的月份吧,因为迎来了难得的暑假时光。想几点睡几点睡,想睡到几点睡到几点,想玩什么玩什么,之前...
    闹儿不闹阅读 2,206评论 0 1

友情链接更多精彩内容