Thursday, September 18, 2014

Spring externalized values not resolved in servlet context

If externalized values (@Value(${value.from.properties.file}) exist in a Spring servlet context, then the context will need its own PropertySourcesPlaceholderConfigurer. It's is not enough to have one defined in the parent context.

Values externalized with with the @Value annotation will not be substituted. Instead one will end up with the contents of the annotation's value attribute as the value of the class' String which you are attempting to externalize. In the example below, that would be: ${html.report}

/------------------------------ Spring managed bead ---------------------------------/
@Controller
@RequestMapping("/downloadreport")
public class ReportDownloader {

 @Value("${html.report}") 
 private String reportLocation;

}

Below is the web.xml entries.

/-------------------------------------   web.xml   ------------------------------------/
<!-- application context -->

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml             
        </param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

<!-- serlvet context created with java config -->

  <servlet>
      <servlet-name>service</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
      <init-param>
       <param-name>contextClass</param-name>
       <param-value>
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
       </param-value>
      </init-param>
      <init-param>

       <param-name>contextConfigLocation</param-name>
       <param-value>
        eu.app.spring.mvc.config.WebMvcConfig
       </param-value>

      </init-param>

  </servlet>


Here is the corresponding java config code.

/-------------------------------------   java config file   ------------------------------------/
@Configuration
@EnableWebMvc
@ComponentScan("eu.app.spring.mvc.handler")
@PropertySource("classpath:web/euapp.properties")
public class WebMvcConfig {

 @Bean
 public PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 } 

  

 @Bean
 public InternalResourceViewResolver getInternalResourceViewResolver() {

  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/jsp/");
  resolver.setSuffix(".jsp");
  return resolver;   

 }

}