自定义 Spring @Profile 注解

Custom Spring @Profile annotation

我正在将我的 @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的新版本中,即使 属性 spring.profiles.active=demoConnector.

也会加载所有带有 @SapConnectorProfile 注释的 beans

在新的 Spring 中不能再这样做了?

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

感谢您的帮助。

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

当我使用时一切正常:

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

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

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