简体   繁体   English

以编程方式初始化春豆

[英]Initialize spring beans programmatically

At the office we are making spring maven web applications and set them up via a WebApplicationInitializer and the AnnotationConfigWebApplicationContext. 在办公室,我们正在制作Spring Maven Web应用程序,并通过WebApplicationInitializer和AnnotationConfigWebApplicationContext对其进行设置。

I have a task that involves initializing beans programmatically. 我的任务涉及以编程方式初始化bean。

I have been trying to use the rootContext to get the bean factory and initialize custom beans manually, but it didn't work and it would tell me that no bean with that name was initialized in app context. 我一直在尝试使用rootContext来获取bean工厂并手动初始化自定义bean,但是它没有用,并且会告诉我在应用程序上下文中没有初始化具有该名称的bean。

Here is my code : 这是我的代码:

public void onStartup(ServletContext sc) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext 
            = new AnnotationConfigWebApplicationContext();

    // my method for adding beans to root context
    registerBeansManually(rootContext, 
            new Class<?>[]{MyEntity1.class, MyEntity2.class}, 
            Map<String,String> mapReadFromSomewhere);

    sc.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext webContext 
            = new AnnotationConfigWebApplicationContext();
    webContext.setParent(rootContext);
    webContext.register(SpringWebConfig.class);

    DispatcherServlet ds = new DispatcherServlet(webContext);
    ServletRegistration.Dynamic registration = sc.addServlet("dispatcher1", ds);
    registration.setLoadOnStartup(1);
    registration.addMapping("/");       
}

And in another method, i try to initialize the beans : 在另一种方法中,我尝试初始化bean:

public void registerBeansManually(AnnotationConfigWebApplicationContext rootContext, 
                                        Class<?>[] entityClasses, 
                                        Map<String,String> dbInfoMap)
    {
        // get the bean factory from the root context
        rootContext.refresh();
        ConfigurableListableBeanFactory beenFactory = rootContext.getBeanFactory();

        // in dbInfo map are the infor for connecting to db
        // produce a DataSource instance and register it as a singleton bean :
        DataSource ds = new DatabaseBeansProducer().produceDataSource(dbInfoMap);
        beanFactory.registerSingleton("myProjectDataSource", ds);

        // using the myProjectDataSource and the entity classes in the method argument
        // produce a SessionFactory and register it as a singleton bean :
        LocalSessionFactoryBean sf = new DatabaseBeansProducer().produceSessionFactory(ds, entityClasses);
        beanFactory.registerSingleton("myProjectSessionFactory", sf);


        // using the myProjectSessionFactory, produce the TransactionManager
        // and register it as a singleton bean :
        HibernateTransactionManager txm = new DatabaseBeansProducer().produceTransactionManager(sf);
        beanFactory.registerSingleton("myProjectTransactionManager", txm);
    }

Like I've said, I suffer from missing beans when I try to initialize them this way, namely, I get an error message saying that I can't @Autowire the 'myProjectSessionFactory' bean because no bean with that name exists in the app context. 就像我说过的那样,当我尝试以这种方式初始化它们时,我会遭受丢失的bean的困扰,即,我收到一条错误消息,提示我无法@Autowire'myProjectSessionFactory'bean,因为应用程序中不存在具有该名称的bean上下文。

How could I do this? 我该怎么办?

I figured it out : 我想到了 :

All i have to do is to put the following annotation on the myProjectSessionFactory bean : 我要做的就是在myProjectSessionFactory bean上放置以下注释:

@Autowired(required=false)
@Qualifier("myProjectSessionFactory")
private SessionFactory sessionFactory;

And i do the same with any bean that complains about not being in the app context. 对于任何抱怨不在应用程序上下文中的bean,我都做同样的事情。

This is happening because when you do a 发生这种情况是因为当您执行

rootContext.refresh();

Spring will try to autowire all the beans within @ComponentScan, and it isn't finding a session factory, because i am initializing it in this savage manner later on. Spring将尝试自动装配@ComponentScan中的所有bean,并且没有找到会话工厂,因为稍后我将以这种野蛮的方式对其进行初始化。

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

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