0

I want to be able to reference environment variables in web.xml, something along the lines of this:

<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.

However, I don't understand how to do that. I've added this 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. How should I define that bean, and how can I use its value in web.xml?

Community
  • 1
  • 1
Adam
  • 928
  • 9
  • 21

1 Answers1

0

If you're willing to forego using XML configuration in favor of Java config it's quite easy to reference environment variables there. Just @Autowire Environment in your config class, then you can do something like

@Autowired
Environment environment;

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

Then just call your bean and you're done. This assumes the property either exists in your environment or you've passed it in with -DSERVER_ENVIRONMENT at runtime.

Or you could just use Spring's @Profile annotation and make your logs environment dependent using that (several tutorials on that also).

Incidentally Spring Boot makes this process even easier.

Arturo Araya
  • 166
  • 1
  • 5