【问题标题】:Spring boot starter web - make a configuration bean that alters properties initialized firstSpring boot starter web - 制作一个配置bean,首先更改初始化的属性
【发布时间】: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


    【解决方案1】:

    您可能正在寻找EnvironmentPostProcessor

    它可以在应用程序上下文启动之前更改环境,我相信这是最清晰的方法。

    这里有一个教程可以帮助您入门:https://blog.frankel.ch/another-post-processor-for-spring-boot/#gsc.tab=0

    【讨论】:

    • 这就是我一直在寻找的答案.. Thnx
    • 如果它解决了您的问题,请不要忘记接受答案。
    • 再次感谢。唯一的小问题是我不能在此类中使用任何 Spring bean 进行 dao 操作(repos anda 等),因为它们尚未创建。但我想这是完全可以接受的,因为我可以在这个类中更改他们的配置....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2017-03-23
    • 1970-01-01
    • 2018-12-24
    • 2016-01-29
    • 1970-01-01
    相关资源
    最近更新 更多