使用java配置初始化spring属性(profile等)的正确方法是什么?

时间:2015-12-30 19:22:15

标签: java spring spring-java-config spring-profiles

我有一个名为initParameters.properties的文件,其中包含一个名为spring.profiles.active的密钥,该密钥正在被过滤,但这还不够,因为Spring还没有知道这个属性。
我正在使用 AbstractAnnotationConfigDispatcherServletInitializer 作为我的WebAppInitializer,这里是它的重要部分:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    setInitParameters(servletContext);
}

@SneakyThrows
private void setInitParameters(ServletContext servletContext) {
    Properties initParams = new Properties();
    initParams.load(new ClassPathResource("initParameters.properties").getInputStream());
    initParams.stringPropertyNames().stream().forEach(propertyName -> CHOOSE_OPTION_HERE);
}

选项1:

servletContext.setInitParameter(propertyName, initParams.getProperty(propertyName))

选项2:

System.setProperty(propertyName, initParams.getProperty(propertyName))

两种方式都有效,我只是不知道它们之间有什么区别,除了一个是系统属性而另一个是initParameter。
Ofc,当我在启动应用程序时设置系统属性-Dspring.profiles.active = someProfile时,它会覆盖所有内容,甚至是我的.properties文件中的过滤,所以一切都很好。
我在互联网上寻找一些解释,利弊但找不到任何东西。
另外,如果有办法直接从.properties文件通知spring属性,我也想知道如何(也就是跳过setInitParameters部分)。我认为Spring Boot会自动检测到它,但我没有使用它,所以想知道Spring中是否有类似的东西。谢谢你的时间。

0 个答案:

没有答案