使用bean定义配置文件的Spring 3.1 bean可见性

我一直在尝试使用Spring 3.1’s bean definition profiles和嵌套bean.我希望我可以根据活动配置文件定义不同的bean.请考虑以下重点简化示例,以便我的Spring上下文包含类似的内容

<bean id="say" class="test.Say" p:hello-ref="hello"/>

<beans profile="prod">
    <bean id="hello" class="test.Hello" p:subject="Production!"/>
</beans>

<beans profile="dev">
    <bean id="hello" class="test.Hello" p:subject="Development!"/>
</beans>

我收到以下错误:

Exception in thread “main”
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘say’ defined in class path resource
[applicationContext.xml]: Cannot resolve reference to bean ‘hello’
while setting bean property ‘hello’; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named ‘hello’ is defined at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
aJava Result: 1

我希望根据活动的Maven配置文件(在我的例子中为prod或dev)来定义hello bean.我开始认为Spring活动配置文件(spring.profiles.active)可能与Maven配置文件完全无关.

有人可以解释我哪里出错吗? (甚至可以使用配置文件?).

最佳答案

I was expecting that the hello bean would be defined according to the active Maven profile (in my case prod or dev). I’m starting to think that the Spring active profiles (spring.profiles.active) may be completely unrelated to Maven profiles.

这是真的,他们是无关的.

以下是如何解决它:

确保src / main / webapp / WEB-INF /文件夹中的web.xml具有以下上下文设置:

<context-param>
    <param-name>spring.profile.active</param-name>
    <param-value>${profileName}</param-value>
</context-param>

然后确保maven-war-plugin为web.xml启用了过滤功能:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
    </configuration>
</plugin>

最后在你的个人资料中:

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <profileName>dev</profileName>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <profileName>prod</profileName>
        </properties>
    </profile>
</profiles>

您还可以在普通属性部分中添加默认值:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <profileName>dev</profileName>
</properties>

因此,如果在没有-P选项的情况下运行,将使用开发弹簧配置文件.

运行mvn包时,web.xml将具有spring.profile.active的正确值.

转载注明原文:使用bean定义配置文件的Spring 3.1 bean可见性 - 代码日志