自定义Spring @Profile注解

6

我正在将我的 @SpringBootApplication 应用程序从 Spring Boot 1.5 更新到 2.2,同时将 Spring 4.3 更新到 5.2,但使用自定义的 @Profile 注解时出现了问题。

在旧版本中,我有一个注解

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

所有属于"SapConnector"的豆子都带有"@SapConnectorProfile"注释。当我运行应用程序时,我只需定义属性"spring.profiles.active=sapConnector",它就会加载带有此注释的豆子。如果我将属性更改为例如"spring.profiles.active=demoConnector",则不会加载任何带"@SapConnectorProfile"注释的豆子。
在新版本的Spring中,所有带有"@SapConnectorProfile"注释的豆子都会被加载,即使属性"spring.profiles.active=demoConnector"。
在新的Spring中不再可能这样做了吗?
如果使用注释"@Profile("sapConnector")"代替"@SapConnectorProfile",则配置文件正常工作。
感谢您的帮助。

注解处理在5.2中进行了重新设计,因此可能存在回归问题。请使用最新的Spring Boot 2.2.1快照进行检查,因为我们已经在这个领域修复了一些问题。如果仍然失败,请创建一个带有小样本的问题 https://github.com/spring-projects/spring-framework - Stephane Nicoll
1
它也不能与2.2.1.BUILD-SNAPSHOT一起使用。我刚试过了。很好地捕捉到了,Pavel。这是一个重大的错误。像@Stephane提到的那样,请创建一个问题。 - pvpkiran
2个回答

4

但是@Profile已经有@Retention(RetentionPolicy.RUNTIME)了,为什么我们还需要显式声明呢? - theprogrammer

1

只需在您的自定义注释上添加@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”错误。

5
你说得对,但这几乎与一年前被接受的答案(https://dev59.com/0Lfna4cB1Zd3GeqPmx0l#58655067)相同——你只是额外提到要在所需的bean内使用注释(我认为这是显而易见的)。 - de-jcup

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接