从数据库或 Java 对象动态加载 spring bean 属性) [英] Dynamically load spring bean properties from database or Java Objects )

查看:26
本文介绍了从数据库或 Java 对象动态加载 spring bean 属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我需要将数据库或 java 对象中的属性加载到 bean 中.

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

考虑这个例子:

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

而不是从属性文件加载值的 ${DEMO_KEY} 属性占位符,我需要从数据库加载一个值,我使用 Java 中的存储过程检索该值班级.

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.

请给我建议一种机制,我可以利用它来处理上述情况.目前我正在研究扩展 SpringMain 和/或 PropertyPlaceholderConfigurer 类并编写我自己的自定义 BootStrapper.

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.

还请提出有关为上述场景编写 BootStrapper 的提示.

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

推荐答案

Java 配置似乎是一个不错的选择的情况之一:

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

}

请注意,您可以将 DataSource(或 JdbcTemplate)注入到您的 @Configuration 类中,前提是它是在别处定义的.

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

这篇关于从数据库或 Java 对象动态加载 spring bean 属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆