Use wildcard in @Profile

Viewed 2121

How can I use wildcard in @Profile?

For example:

@Profile("*-from-db")
private class Foo {

Foo bean should be activated when the spring.profiles.active is ended with "-from-db"; like dev-from-db, qa-from-db, prod-from-db, etc.

2 Answers

As said by others, this isn't possible using the @Profile annotation and can only be done by implementing your own Condition.

To do that, you need to create an annotation (eg. @ConditionalOnProfileSuffix) and create an implementation of Condition (the easiest way is by extending from SpringBootCondition).

After that you have to annotate your conditional annotation with the @Conditional annotation, for example:

@Conditional(OnProfileSuffixCondition.class)

Within OnProfileSuffixCondition (the implementation of SpringBootCondition), you can retrieve the active profiles by using:

conditionContext.getEnvironment().getActiveProfiles()

To retrieve the values from the annotation you can use:

annotatedTypeMetadata.getAllAnnotationAttributes(ConditionalOnProfileSuffix.class.getName()); 

This will return a MultiValuedMap where the key is the annotation property name, and the value is any object (depends on the type).

Related