【发布时间】:2018-04-23 10:07:44
【问题描述】:
我在我的 Spring Boot 应用程序中使用嵌入式 tomcat。我的要求是从 db 以及属性文件中读取所有配置属性。
我设法从 db 读取属性并使用 @Configuration bean 将属性附加到 MutablePropertySources,如下所示:
@Configuration
public class PropertiesConf {
@Autowired
private Environment env;
@Autowired
private ApplicationContext appContext;
@PostConstruct
public void init() {
MutablePropertySources propertySources = ((ConfigurableEnvironment) env).getPropertySources();
ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
DataSource ds = (DataSource) appContext.getBean("confDBBeanName");
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
//read config elements from db
//List<IntegraProperties> list = ..
list.forEach(entry -> map.put(entry.getKey(), entry.getValue()));
MapPropertySource source = new MapPropertySource("custom", map);
propertySources.addFirst(source);
}
}
问题是这个配置是在 servlet(例如cxf servlet)注册之后初始化的。以下配置是从我的 application.properties 文件中的 cxf.path=/api2 读取的:
2017-11-10 09:41:41.029 INFO 7880 --- [ost-startStop-1] osbwservlet.ServletRegistrationBean:将 servlet:'CXFServlet' 映射到 [/api2/]*
如您所见,当我添加配置属性时,为时已晚。在我添加配置之前会进行一些初始化。
如何确保我的 bean (PropertiesConf) 在启动期间首先初始化并更改属性,以便它们在系统范围内适用于所有 bean?
目前我正在向我所有的 bean 添加以下 DependsOn 注释,这非常讨厌......
@DependsOn("propertiesConf")
但我仍然有 servlet 等问题。
正确的弹簧方式是什么
【问题讨论】:
标签: java spring tomcat spring-boot spring-boot-starter