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

Mar*_*ren 7 java spring maven applicationcontext

我一直在尝试使用Spring 3.1的bean定义配置文件和嵌套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>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

线程"main"中的异常org.springframework.beans.factory.BeanCreationException:在类路径资源[applicationContext.xml]中定义名称为'say'的bean时出错:在设置bean属性'hello'时无法解析对bean'hello'的引用; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:在org.springframework.beans.factory的org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)中没有定义名为'hello'的bean. .support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:

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

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

mab*_*aba 12

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

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

以下是如何解决它:

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

<context-param>
    <param-name>spring.profile.active</param-name>
    <param-value>${profileName}</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

然后确保maven-war-plugin为以下内容启用了过滤web.xml:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
    </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

最后在你的个人资料中:

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <profileName>dev</profileName>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <profileName>prod</profileName>
        </properties>
    </profile>
</profiles>
Run Code Online (Sandbox Code Playgroud)

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

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <profileName>dev</profileName>
</properties>
Run Code Online (Sandbox Code Playgroud)

因此,如果在没有-P选项的情况下运行,dev将使用弹簧轮廓.

当运行mvn packageweb.xml将会对正确的值spring.profile.active.