我想加载一个与contextPath同名的配置文件。这是我试过的代码:
@Configuration
@PropertySource("file:${user.home}/#{servletContext.contextPath}.properties")
public class PropertiesConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer()
{
return new PropertySourcesPlaceholderConfigurer();
}
}
上述代码不起作用,因为#{servletContext.contextPath}
未解决。
有一种简单的方法吗?
答案 0 :(得分:1)
@EnableWebMvc
@Configuration
@PropertySource("classpath:/my.properties")
public class MyConfig {
public @Value("#{ servletContext.getContextPath() }") String test;
}
答案 1 :(得分:0)
servletContext
似乎无法访问@PropertySource
。解决方法是使用@Value
来获取contextPath值。
@Configuration
public class PropertiesConfiguration {
@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(
@Value("#{servletContext.contextPath}") String contextPath) throws MalformedURLException
{
final PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setLocation(new UrlResource("file:" + System.getProperty("user.home") + "/" + contextPath + ".properties"));
return configurer;
}
}