Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Spring profile name from annotation?

Tags:

java

spring

With Spring 3.1 and profiles, creating a custom interface to define specific profiles becomes interesting. Part of the beauty is the ability to completely forgot the String name of the profile and just use the annotation.

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

}

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

However, how can I check if the @Dev profile is active? Environment.acceptsProfiles() requires a String argument. Is there a "neat" way of doing this, or is my only option 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
        ;
    }

Although functional, I'm not particularly fond of this concept. Is there another way I can do this neater?

like image 818
Eric B. Avatar asked Sep 27 '22 00:09

Eric B.


1 Answers

I wanted to do something similar (in my case, represent a list of synonyms under one profile annotation) but I ran into the problem your having, as well as another limitation: You won't be able to apply more than one of the annotations to a single bean and have them both get picked up by spring (at least in spring 3).

Unfortunately, as you cannot pass the enum in, the solution I settled on was to just use plain-old string constants without the enum. Then I could do something like @Profile(CONSTANT_ONE, CONSTANT_TWO). I still benefited from not being able to make typos, but also gained the ability to still apply multiple profiles to the same bean.

Not perfect, but not too bad.

like image 97
leeor Avatar answered Nov 01 '22 12:11

leeor