概要文件不活动时包括Bean定义 [英] Including bean definition when a profile is NOT active
问题描述
在我的应用程序中,我使用了几个个人资料使某些bean可以自动装配.我所缺少的是,当某个配置文件处于非活动状态时,是否有可能使bean符合自动装配的条件.
In my application I use several profiles to make certain beans eligible for autowiring. What I'm missing is the possibility to make a bean eligible for autowiring when a certain profile is NOT active.
我想到的最好的方法是这样的:
The best way of doing it that I thought about is like this:
- 假设我们有所有可能的配置文件的列表,例如{A,B,C,D}.
- 为执行特定活动而活动的配置文件为{A,C}.
- 我要做的是为所有未激活的可能的配置文件创建人工配置文件.在示例情况下,我将创建{not_B,not_D}配置文件.
- 我要基于未激活的配置文件
X
来激活的Bean,我使配置文件not_X
处于激活状态.在我的情况下,如果我希望在配置文件B处于不活动状态时有资格进行自动装配的Bean,则可以对它们进行注释@Profile("not_B")
- Let's suppose we have a list of all possible profiles, e.g. {A, B, C, D}.
- Profiles active for particular execution are {A, C}.
- What I do is I create artificial profiles for all possible profiles which are not active. In the example case I would create {not_B, not_D} profiles.
- The beans I want to be active based on not active profile
X
I make active for profilenot_X
. In my case if I wanted a bean to be eligible for autowiring when profile B is not active, I would annotate them@Profile("not_B")
但是,此解决方案需要有关所有可能的配置文件的预备知识.
This solution however requires an up-front knowledge about all possible profiles.
您能想到更好的解决方案吗?
Can you think of any better solution?
推荐答案
可以使用not(!)运算符...,但是必须使用Spring 3.2 M1.
You can use a not (!) operator... but you have to use Spring 3.2 M1.
现在支持以下语法
The following syntax is now supported
<beans profile="A,!B">
@Profile("A", "!B")
指示仅在概要文件"A"处于活动状态或概要文件"B"处于非活动状态时才应处理元素或带注释的组件.
indicating that the element or annotated component should be processed only if profile 'A' is active or profile 'B' is not active.
请参阅此处宣布的更改: Spring Framework 3.2 M1发布
提交在GitHub上:不支持(!)运算符来选择配置文件
JIRA中的问题: SPR-8728
See change announced here: Spring Framework 3.2 M1 Released
The commit is at GitHub: Support not (!) operator for profile selection
Issue in JIRA: SPR-8728
如果您的项目无法升级到Spring 3.2,建议不要使用@Profile
方法,并确保未在Spring配置中创建Bean.
If upgrading to Spring 3.2 is not possible for your project, I would recommend not using the @Profile
approach and ensuring that the bean is not created in your Spring configuration.
这篇关于概要文件不活动时包括Bean定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!