Pavel Spicak
Pavel Spicak

Reputation: 111

Custom Spring @Profile annotation

I am updating my @SpringBootApplication application from Spring Boot 1.5 to 2.2 and Spring 4.3 to 5.2 and I am having issues with a custom @Profile annotations.

In the older version, I had annotation

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

and every bean that belongs to "sapConnector" was annotated with the @SapConnectorProfile annotation. When I was running the application I simply defined property spring.profiles.active=sapConnector and it loads the beans annotated with this annotation. And if I changed the property to f.e. spring.profiles.active=demoConnector it does not load any bean with @SapConnectorProfile annotation.

In the new version of Spring, all beans annotated with @SapConnectorProfile are loaded even if the property spring.profiles.active=demoConnector.

It is not possible to do this anymore in the new Spring?

The profiles work fine if I use annotation @Profile("sapConnector") instead of @SapConnectorProfile.

Thank you for help.

Upvotes: 6

Views: 1898

Answers (2)

Renzo
Renzo

Reputation: 11

Just add @Retention(RetentionPolicy.RUNTIME) on your custom annotation.

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

}

And dont forget annotate your bean candidate

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

Else you'll get org.springframework.beans.factory.NoUniqueBeanDefinitionException

Upvotes: 1

Pavel Spicak
Pavel Spicak

Reputation: 111

I was missing @Retention(RetentionPolicy.RUNTIME) annotation.

Everything works fine when I use:

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

Issue I have created: https://github.com/spring-projects/spring-framework/issues/23901

Upvotes: 4

Related Questions