读取AbstractAnnotationConfigDispatcherServletInitializer的子类中的属性

时间:2016-01-12 21:55:11

标签: spring spring-mvc properties spring-java-config

Spring version 4.2.2,我想从属性文件中读取上传文件位置,尝试添加@PropertySource

@PropertySource("/WEB-INF/conf/my.properties")
public class MyWebAppInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

@Value("${upload.location}")
String loc;

...

@Override
protected void customizeRegistration(Dynamic registration) {
    registration.setMultipartConfig(new MultipartConfigElement(
            loc, 2097152, 4194304, 0));
}
}

没有工作

也试过这个:

@PropertySource("/WEB-INF/conf/my.properties")
public class MyWebAppInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

@Resource
Environment env;

...

@Override
protected void customizeRegistration(Dynamic registration) {
    String loc = env.getProperty("upload.location");
    registration.setMultipartConfig(new MultipartConfigElement(
            loc, 2097152, 4194304, 0));
}
}

有没有办法在这里注入属性?

1 个答案:

答案 0 :(得分:0)

通常我使用bean声明属性文件,如下所示:

@Bean(name = "PropertiesFile")
public static PropertyPlaceholderConfigurer properties() {
    PropertyPlaceholderConfigurer placeholder = new PropertyPlaceholderConfigurer();
    ClassPathResource[] value = new ClassPathResource[] { new ClassPathResource("/WEB-INF/conf/my.properties") };
    placeholder.setLocations(value);
    return placeholder;
}

之后就像你一样使用@Value

希望它有所帮助。