简体   繁体   中英

loading Spring profiles from database

One may dynamically load Spring profiles by implementing ApplicationContextInitializer and adding Spring profiles to the environment.

The problem is that in one of projects I am helping in they are using properties stored in database. How to load property representing additional active Spring profiles from the database and than injecting it to the environment. In ApplicationContextInitializer I cannot use Spring beans because the application context is not yet fully initialized. Is low level access to the database my only option?

Spring PropertyPlaceholderConfigurer needs to be initialized with a location property that is the properties file you want. But, this class can be also initialized with a java.util.Properties object.

From deprecated project Spring-Modules, you can find here this class that implements InitializingBean and FactoryBean Spring clases, such way it behaves like a normal java.util.Properties object which can be passed on to PropertyPlaceholderConfigurer.setProperties() method.

This way you can take advantage of org.apache.commons.configuration.DatabaseConfiguration which acts like a Properties object but reading properties from a database. For example, think of this bean configuration:

<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>

Here, arg 1 is the table that contains the properties, arg 2 the key column ans arg 2 the value column.

So, you can create your custom class, very similar to CommonsConfigurationFactoryBean and use in this way:

<bean 
    name="PropertyPlaceholderConfigurer"     
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties" ref="MyCustomClass"/>
</bean>

Where MyCustomClass is the class you will use to wrap MyDatabaseConfiguration .

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM