How to get Spring profile name from annotation?

With Spring 3.1 and profiles, it becomes interesting to create a custom interface for defining specific profiles. Part of the beauty is the ability to completely forget the profile line name and just use annotation.

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Profile("Dev") public @interface Dev { } 

And then just annotate beans with @Dev . This works great.

However, how to check if the @Dev profile is @Dev ? Environment.acceptsProfiles() requires a String argument. Is there a β€œneat” way to do this, or is my only way to do something like:

 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Profile(Dev.NAME) public @interface Dev { public static String NAME = "Dev"; } public class MyClass{ @Autowired private Environment env; private void myMethod(){ if( env.acceptsProfiles( Dev.NAME ) ) // do something here ; } 

Despite the functionality, I do not really like this concept. Is there any other way to make this better?

+4
source share
1 answer

I wanted to do something like this (in my case, I present a list of synonyms under one profile annotation), but I ran into a problem related to you, as well as another restriction: you cannot apply more than one from annotations to one bean, and they are both obtained using spring (at least in spring 3 ).

Unfortunately, since you cannot pass enum in, the solution I settled on was to simply use simple text constants without an enumeration. Then I could do something like @Profile(CONSTANT_ONE, CONSTANT_TWO) . I still benefited from the inability to make typos, but also got the opportunity to still apply multiple profiles to the same bean.

Not perfect, but not so bad.

+3
source

All Articles