简体   繁体   English

如何从注释中获取Spring配置文件名称?

[英]How to get Spring profile name from annotation?

With Spring 3.1 and profiles, creating a custom interface to define specific profiles becomes interesting. 使用Spring 3.1和配置文件,创建定义特定配置文件的自定义界面变得有趣。 Part of the beauty is the ability to completely forgot the String name of the profile and just use the annotation. 美的一部分是能够完全忘记配置文件的String名称并只使用注释。

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

}

And then simply annotate beans with @Dev . 然后使用@Dev简单地注释bean。 This works great. 这非常有效。

However, how can I check if the @Dev profile is active? 但是,如何检查@Dev配置文件是否处于活动状态? Environment.acceptsProfiles() requires a String argument. Environment.acceptsProfiles()需要String参数。 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? 还有另一种方法我可以做这个整洁的?

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 ). 我想做类似的事情(在我的情况下,代表一个配置文件注释下的同义词列表)但我遇到了你遇到的问题,以及另一个限制:你将无法应用多个注释到一个豆子,让它们都被spring捡起来(至少在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) . 然后我可以做像@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. 我仍然无法进行拼写错误,但也获得了将多个配置文件应用于同一个bean的能力。

Not perfect, but not too bad. 不完美,但也不是太糟糕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM