[英]loading Spring profiles from database
通过实现ApplicationContextInitializer并将Spring配置文件添加到环境中,可以动态加载Spring配置文件。
问题是在我正在帮助的一个项目中,他们正在使用存储在数据库中的属性。 如何从数据库中加载表示其他活动Spring概要文件的属性,然后将其注入环境。 在ApplicationContextInitializer中,由于应用程序上下文尚未完全初始化,因此我无法使用Spring Bean。 低级访问数据库是我唯一的选择吗?
Spring PropertyPlaceholderConfigurer
需要使用一个位置属性初始化,该属性是所需的属性文件。 但是,也可以使用java.util.Properties
对象初始化该类。
从弃用项目Spring的模块,你可以在这里找到这个类实现InitializingBean
和FactoryBean
春天clases,它的行为像一个正常的这样的方式java.util.Properties
对象,它可以被传递到PropertyPlaceholderConfigurer.setProperties()
方法。
这样,您就可以利用org.apache.commons.configuration.DatabaseConfiguration
,该属性的行为类似于Properties对象,但从数据库中读取属性。 例如,考虑以下bean配置:
<bean
name="MyDatabaseConfiguration"
class="org.apache.commons.configuration.DatabaseConfiguration">
<constructor-arg type="javax.sql.DataSource" ref="someDataSource"/>
<constructor-arg index="1" value="SCHEMA.PROPERTIES_TABLE"/>
<constructor-arg index="2" value="KEY"/>
<constructor-arg index="3" value="VALUE"/>
</bean>
在这里,arg 1是包含属性的表,arg 2是键列,而arg 2是值列。
因此,您可以创建与CommonsConfigurationFactoryBean
非常相似的自定义类,并以这种方式使用:
<bean
name="PropertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="MyCustomClass"/>
</bean>
其中MyCustomClass
是用于包装MyDatabaseConfiguration
。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.