Search code examples
javaspringspring-bootjava-8javabeans

How to conditionally enable a class in Spring if active profile matches a regex keyword?


I have a Spring Boot Controller and I want to enable it only when certain profiles are active. However instead of hardcoding all these profiles I want to use regex or some other way to do this.

Consider this piece of code

@Controller
@Profile("#{'spring.profiles.active' matches 'eu'}") // this line is not working
public class HomeController{
// ... removed other code for brevity
}

Now I want this controller to be enabled only if active profile belongs to anything like this: dev1_eu, dev2_eu, dev3_eu, qa1_eu, qa2_eu, qa3_eu, prod1_eu, prod2_eu, prod3_eu, test1_eu, test2_eu etc. "Etc" is the keyword here. I have many more profiles which all have eu in them and I want the above controller to be enabled only in such *eu* profiles. Now whether having these many profiles is a good practice or not is up for debate, but assume that this cannot be changed(i.e., number of profiles cannot be reduced). Since if number of profiles were less, I would probably do something like this:

@Profile({"dev_eu","qa_eu","prod_eu"})

How would one go about doing this? If @Profile is not the way, what are some other cleaner/easy ways to achieve this?


Solution

  • You can try @ConditionalOnExpression

    @ConditionalOnExpression(value = "#{ '${spring.profiles.active}' matches 'pattern' }")