简体   繁体   English

春天如何在web.xml中使用环境变量?

[英]How to use environment variables in web.xml in spring?

I want to be able to reference environment variables in web.xml, something along the lines of this: 我希望能够在web.xml中引用环境变量,类似于以下内容:

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:conf/log4j-${SERVER_ENVIRONMENT}.properties</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.util.Log4j2ConfigListener</listener-class>
</listener>
<param-value>classpath:conf/log4j-​${SERVER_ENVIRONMENT}​.properties</param-value>

This question is similar to mine, and the most upvoted answer claims that: 这个问题与我的相似,最受支持的答案声称:

If you are using Spring, you can create a bean and then directly use envvars or sysprops in Spring XML config files. 如果您使用的是Spring,则可以创建一个bean,然后在Spring XML配置文件中直接使用envvars或sysprops。

However, I don't understand how to do that. 但是,我不知道该怎么做。 I've added this bean: 我添加了这个bean:

<context:property-placeholder />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="serverEnvironment" value="${SERVER_ENVIRONMENT}"></property>
    <property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

But I don't know if I'm doing it right, nor how to access that variable from web.xml. 但是我不知道我是否做对了,也不知道如何从web.xml访问该变量。 How should I define that bean, and how can I use its value in web.xml? 我应该如何定义该bean,以及如何在web.xml中使用其值?

If you're willing to forego using XML configuration in favor of Java config it's quite easy to reference environment variables there. 如果您愿意放弃使用XML配置而转而使用Java配置,则可以很容易地在那里引用环境变量。 Just @Autowire Environment in your config class, then you can do something like 只需在配置类中使用@Autowire Environment,那么您可以执行类似的操作

@Autowired
Environment environment;

@Bean
public String getServerEnvironment(){
   return this.environment.getProperty("SERVER_ENVIRONMENT");
}

Then just call your bean and you're done. 然后只需调用您的bean就可以了。 This assumes the property either exists in your environment or you've passed it in with -DSERVER_ENVIRONMENT at runtime. 这假定该属性在您的环境中存在,或者您已在运行时使用-DSERVER_ENVIRONMENT传递了该属性。

Or you could just use Spring's @Profile annotation and make your logs environment dependent using that (several tutorials on that also). 或者,您可以仅使用Spring的@Profile批注,并使用该批注使您的日志环境依赖(也有一些教程)。

Incidentally Spring Boot makes this process even easier. 顺便说一句,Spring Boot使此过程更加容易。

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

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