在Spring Java Config类中读取上下文参数

时间:2014-08-31 05:44:00

标签: spring

我在tomcat上下文文件中定义了一个参数 -

<Parameter name="filePath" value="C:/test/test.properties" override="false"/>

我想使用contextParameter bean在Spring的Configuration类中读取此参数但我得到null值。请建议如何在本课程中阅读此值。当我在任何其他课程中做同样的事情时,我得到了预期的价值。我的代码如下:

@Configuration
@EnableWebMvc
public class WebAppConfig {

//Using value annotation and contextParameter bean for reading value
@Value("#{contextParameters.filePath}")
private String filePath;

// Want to use that context Parameter to load propertiy file
@Bean
public  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {

    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurerBean = new PropertySourcesPlaceholderConfigurer();     
    propertySourcesPlaceholderConfigurerBean.setLocations(new Resource[]{new FileSystemResource(filePath)});
    return propertySourcesPlaceholderConfigurerBean;
}

1 个答案:

答案 0 :(得分:1)

该属性应该通过Environment提供,这意味着您应该可以直接引用它:

@Value("${filePath}")
private String filePath;

或通过自动装配的环境bean获取,例如:

@Bean
public String filePath(Environment environment) { 
    return environment.getProperty("filePath");
}

@Value("#{filePath}")
private String filePath;