kanap008
kanap008

Reputation: 2820

Dynamically load spring bean properties from database or Java Objects )

I have a scenario where I need to load properties from database or java object into beans.

Consider the example:

<bean id="ConfigAsstDemoBeanParent" class="gps.springconfig.DemoClass" lazy-init="true">
  <property name="demoValueFromBean" value="demoValue"></property>
  <property name="demoValueForKeyFromProperties" value="${DEMO_KEY}"></property>
</bean>

and instead of the ${DEMO_KEY} property placeholder, which loads a value from the property file, I need to load a value from the database, which I retrieve using a stored procedure from a Java class.

Please suggest me a mechanism which I can leverage for the above scenario. Currently I am investigating extending SpringMain and/or PropertyPlaceholderConfigurer class and write my own custom BootStrapper.

Also please suggest hints on writing a BootStrapper for the above mentioned scenario.

Upvotes: 4

Views: 9999

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

One of the cases where Java configuration seems to be a great alternative:

@Configuration
public class Config {

    @Resource
    private DataSource dataSource;

    @Bean
    @Lazy
    public DemoClass configAsstDemoBeanParent() {
        DemoClass demo = new DemoClass();
        demo.setDemoValueFromBean("demoValue");
        demo.demoValueForKeyFromProperties( /* query the database here */);
        return demo;
    }

}

Note that you can inject DataSource (or JdbcTemplate) to your @Configuration class providing it was defined elsewhere.

Upvotes: 7

Related Questions