【发布时间】:2015-11-22 21:33:25
【问题描述】:
我在Spring, Java, Ant 网络应用程序中工作。我正在使用 Spring 分析来加载基于环境的属性。下面是示例
@Profile("dev")
@Component
@PropertySource("classpath:dev.properties")
public class DevPropertiesConfig{
}
@Profile("qa")
@Component
@PropertySource("classpath:qa.properties")
public class TestPropertiesConfig {
}
@Profile("live")
@Component
@PropertySource("classpath:live.properties")
public class LivePropertiesConfig{
}
在web.xml中,我们可以给出profile
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
现在,我的查询是针对我需要创建一个单独的 Java 类的每个环境。
问题:是否可以只有一个类,例如提供配置文件名称作为一些绑定参数,例如@Profile({profile})。
另外,如果有其他更好的选择可以达到同样的效果,请告诉我。
【问题讨论】:
-
是的,这是可能的,而且你做得对。
-
代替这个使用
ApplicationContextInitializer,它基于活动的配置文件添加一个指向该配置文件的ResourcePropertySource。这也是 Spring Boot(或多或少)所做的。 -
有关@M.Deinum 答案的详细示例,请参阅此SO answer。
-
我已经删除了我的解决方案,因为它是硬编码配置文件名称。您可以在上面的 SO 答案链接中参考解决方案。
-
@M.Deinum,是否可以创建单个 bean 来加载属性文件。由于 OP 必须使用 3 个单独的类。
标签: java spring spring-mvc properties-file spring-profiles