【问题标题】:How can I inject Spring parameters based on Maven profile如何根据 Maven 配置文件注入 Spring 参数
【发布时间】:2015-03-30 14:31:18
【问题描述】:

我想基于 Maven 配置文件将基于 Spring 环境的值(例如用于 dev、stage、prod 的 URL)注入我的 Spring xml。

我看到了一些相关问题,例如 this on DI using Maventhis on switching environments,但我没有看到如何根据 Maven 配置文件注入基于环境的值的具体示例。

有人可以指导我吗。

【问题讨论】:

    标签: spring maven dependency-injection


    【解决方案1】:

    听起来你只需要使用PropertyPlaceholderConfigurer

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    </bean>
    <bean id="greetings" class="Greeting">
        <property name="message" value="${greeting}" />
    </bean>
    

    这会将greeting 系统属性注入您的bean。然后您的 Maven 配置文件可以定义将被注入的系统属性。

    根据您使用的 Spring 版本(尽管根据您的 XML bean 定义,这听起来像是一个较旧的版本),我很想使用 Maven 配置文件来选择一个 Spring 配置文件。例如,您可以定义-Dspring.profiles.active=dev 并将您的配置放入application-dev.properties

    【讨论】:

    • 出于不同的原因,我已经在此应用程序中使用 PropertyPlaceholderConfigurer,但我不确定它为您提供的解决方案添加了什么。我的意思是,听起来即使没有 PropertyPlaceholderConfigurer,您的解决方案也可以工作!
    • 拥有PropertyPlaceHolderConfigurer 意味着使用${env.var.name} 语法在XML(和Java)中注入环境属性。
    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 2018-07-15
    • 2016-03-21
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多