繁体   English   中英

如何在加载spring上下文之前在应用程序启动时创建bean?

[英]how do I create bean at application startup before loading spring context?

我想以编程方式创建数据源bean,具体取决于从用户传递的args

public class Main {
    public static void main( String[] args ) throws IOException, InterruptedException {     
        //TODO load proper configs depending on args 
        //TODO initiate dataSource bean with UN and PS in args
        ApplicationContext context = new ClassPathXmlApplicationContext( "config/applicationContext-common.xml" );
   }
}

我已经做了一些谷歌搜索,发现我必须创建一个后处理器bean,它创建一个数据源bean并使用获取的数据以编程方式配置它。 我想看到的是一个真实的例子。

您可以尝试下面的代码,它应该在连接之前注入dataSource。

public class Main {
    public static void main( String[] args ) throws IOException, InterruptedException {     
        //TODO load proper configs depending on args 
        //TODO initiate dataSource bean with UN and PS in args
        ApplicationContext context = new ClassPathXmlApplicationContext("config/applicationContext-common.xml") {
          protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
           super.prepareBeanFactory(beanFactory);
           beanFactory.registerSingleton("dataSource", dataSource);
          }
        };
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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