Spring-boot应用程序配置

时间:2014-05-07 08:20:56

标签: spring-boot

我理解如何配置spring-boot并且它提供了一个成熟且合理的覆盖机制,但是我正在转换一个应用程序,该应用程序从不同于spring-boot机制的其他源获取其配置。

最终,应用程序使属性可用于可以使用@Value(“$ the.prop.key:default”)绑定的代码,或者在spring xml config中使用。检索和绑定这些属性的方式无法更改。

我正在尝试配置嵌入式tomcat服务器端口,但我能做到这一点的唯一方法是使用application.properties。我可以将其更改为其他文件甚至更改位置但我无法更改机制(它必须是文件)。

查看spring-boot代码,我看到它使用EmbeddedServletContainerCustomizer实现的概念来设置这些属性。好的,我将创建一个实现并使用它来设置服务器属性。但不幸的是,你有两个实现尝试做同样的事情ServerProperties和我的实现。代码对这些进行排序,但由于ServerProperties没有排序,因此将其设置为最低优先级,并且最后执行低优先级,因此我的实现会被覆盖。

相反,我实现了一个BeanPostProcessor:

@Named
public class SpringBootCustomConfigurator implements BeanPostProcessor {

@Value("$the.prop.key:8080")
private int port;

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
        throws BeansException {
    if (bean instanceof ServerProperties) {
        ServerProperties serverProperties = (ServerProperties) bean;
        serverProperties.setPort(port);
    }
    return bean;
}
}

这就是我需要做的事情,但这不是一个令人满意的实施。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

鉴于它是关于外部属性的新来源,我认为编写一个ApplicationContextInitializer(或ApplicationListener来监听启动时的一个Spring Boot事件)会更自然在正确的位置为您的PropertySource添加新的Environment。您可以使用SpringApplication或使用META-INF/spring.factories注册初始使用者。

相关问题