我目前正在尝试将现有的 spring 应用程序移动到 spring-boot ,从而重新创建无需启动即可工作的内容。
我想从外部源配置一些属性(如 spring.datasource.*)。具体来说是一个包含多个属性文件的文件夹。
我设置了一个配置类来创建 propertyPlaceholder 配置器,如下所示:
@Configuration
public class PropertySourceConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer defaultsPlaceHolderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
propertyConfigurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/*-defaults.properties"));
propertyConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyConfigurer;
}
@Bean
public static PropertySourcesPlaceholderConfigurer externalPlaceHolderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
propertyConfigurer.setLocations(new
PathMatchingResourcePatternResolver().getResources("file:/my-config-path/*.properties"));
propertyConfigurer.setOrder(1);
propertyConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyConfigurer;
}
这似乎适用于大多数事情(例如 amqp 或我自己的配置属性),但是当我尝试使用 spring-data-jpa 时,它们会被忽略。基本设定spring.datasource.url
这些文件中的(以及用于自动配置的其他内容)无效。
查看日志PropertySourcesPropertyResolver
我发现这些配置器属于localProperties
查找时未使用的组spring.datasource.*
.
有没有办法解决这个问题,或者有更好的方法将外部属性文件添加到我的上下文中?
我知道我可以设置spring.config.location
做类似的事情,但我无法将命令行属性传递到我的应用程序,并且需要从我的应用程序内执行此配置。据我所知,此属性不可能做到这一点。
EDIT:环境spring.config.location
:
尝试1:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CampaignServiceStarter.class);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setInitParameter("spring.config.location", "file:/my-config-path/*.properties");
}
}
尝试2:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CampaignServiceStarter.class).properties("spring.config.location=file:/my-config-path/*.properties");
}
}
在这两种情况下,外部属性根本没有被拾取(即使在它之前工作的地方,比如 amqp 配置)