【问题标题】:Custom Spring @Profile annotation自定义 Spring @Profile 注解
【发布时间】:2019-10-25 08:31:47
【问题描述】:

我正在将我的 @SpringBootApplication 应用程序从 Spring Boot 1.5 更新到 2.2,将 Spring 4.3 更新到 5.2,我遇到了自定义 @Profile 注释的问题。

在旧版本中,我有注释

@Profile("sapConnector")
   public @interface SapConnectorProfile {
}

并且属于“sapConnector”的每个 bean 都使用 @SapConnectorProfile 注释进行了注释。当我运行应用程序时,我只定义了属性spring.profiles.active=sapConnector,它加载了带有此注释的bean。如果我将属性更改为 f.e. spring.profiles.active=demoConnector 它不会加载任何带有 @SapConnectorProfile 注释的 bean。

在新版本的 Spring 中,所有带有 @SapConnectorProfile 注释的 bean 都会被加载,即使属性 spring.profiles.active=demoConnector 也是如此。

新春不能再这样了?

如果我使用注释 @Profile("sapConnector") 而不是 @SapConnectorProfile,配置文件可以正常工作。

感谢您的帮助。

【问题讨论】:

  • 注解处理在 5.2 中被重新设计,所以这可能是一个回归。您能否查看最新的 Spring Boot 2.2.1 快照,因为我们已经修复了这方面的一些问题。如果仍然失败,您能否用一个小样本创建一个问题github.com/spring-projects/spring-framework
  • 它也不适用于 2.2.1.BUILD-SNAPSHOT。刚试过。好接球帕维尔。这是一个重大错误。一定要像@Stephane 提到的那样创建一个问题

标签: spring spring-boot annotations


【解决方案1】:

我缺少@Retention(RetentionPolicy.RUNTIME) 注释。

我使用时一切正常:

@Retention(RetentionPolicy.RUNTIME)
@Profile("sapConnector")
public @interface SapConnectorProfile {
}

我创建的问题:https://github.com/spring-projects/spring-framework/issues/23901

【讨论】:

    【解决方案2】:

    只需在您的自定义注释上添加@Retention(RetentionPolicy.RUNTIME)

    @Retention(RetentionPolicy.RUNTIME)
    @Profile("One")
    public @interface FirstMe {
    
    }
    

    别忘了注释你的候选bean

    @Component
    @FirstMe
    public class AMD implements Procesador {
        @Override
        public void tipeArchitecture() {
            System.out.println("AMD Zen 3 [Annotation]");
        }
    }
    

    否则你会得到org.springframework.beans.factory.NoUniqueBeanDefinitionException

    【讨论】:

    • 你是对的,但这与一年前接受的答案几乎相同 - stackoverflow.com/a/58655067/2590615 - 你只是另外提到在想要的 bean 中使用注释(恕我直言,这是显而易见的)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2013-02-24
    • 2013-11-25
    • 2013-05-24
    • 2015-06-21
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多