Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use wildcard in @Profile

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.

like image 276
richersoon Avatar asked Sep 20 '17 09:09

richersoon


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).

like image 60
g00glen00b Avatar answered Nov 08 '22 11:11

g00glen00b


There is no way to do that with only @Profile annotation. You can try with conditional matchers. Please check this post Can I not (!) a collection of spring profiles? and this one https://raymondhlee.wordpress.com/2015/05/31/using-spring-4-condition-to-control-bean-registration/. It should guide you to the right direction.

like image 1
Kamil Avatar answered Nov 08 '22 11:11

Kamil