我正在尝试读取我放在/WEB-INF/config 文件夹下的配置文件。原因是 Jetty Maven 插件不支持资源过滤。有人可以解释我如何使用Spring Java配置功能来做到这一点吗?
我知道<context: property-placeholder ... />
应该工作,但我不想使用 XML。
应用目录
├───META-INF
└───WEB-INF
├───classes
├───config
├───i18n
├───lib
├───pages
└───resources
属性源配置
@Configuration
@EnableWebMvc
@PropertySources({
@PropertySource("log4j.properties"),
@PropertySource("general.properties") }
)
public class ApplicationContext extends WebMvcConfigurerAdapter {
@Autowired
ServletContext servletContext;
@Bean
public PropertyPlaceholderConfigurer properties() {
PropertyPlaceholderConfigurer propertySources = new PropertyPlaceholderConfigurer();
Resource[] resources = new ServletContextResource[] {
new ServletContextResource(servletContext, "WEB-INF/config/log4j.properties"),
new ServletContextResource(servletContext, "WEB-INF/config/general.properties")
};
propertySources.setLocations(resources);
propertySources.setIgnoreUnresolvablePlaceholders(true);
return propertySources;
}
}
例外:
java.lang.IllegalArgumentException: Cannot resolve ServletContextResource without ServletContext
正如 @M.Deinum 所说,没有必要手动配置PropertyPlaceholderConfigurer
:Spring Boot PropertyPlaceholderAutoConfiguration
来处理这个问题。
你需要的一切都@PropertySource
。
由于您的general.properties
位于ServletContext
因此它应该是这样的:
@PropertySource("/WEB-INF/config/general.properties")
请注意,对log4j.properties
做同样的事情并不有意义。考虑将其移动到/WEB-INF/classes
,以允许log4j自动拾取它。
使用以下代码行和@Autowired
注释。
@Autowired
ServletContext servletContext;
String filePath = servletContext.getRealPath("/WEB-INF/XXXX/");
File file = new File(filePath );
FileInputStream fileInput = new FileInputStream(file);