6

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.

1
  • 1
    You cannot... Write your own rule which does that.
    – M. Deinum
    Sep 20, 2017 at 9:53

2 Answers 2

2

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.