Adding a Pre-constructed Bean to a Spring Application Context

后端 未结 6 1921
醉话见心
醉话见心 2020-12-24 02:24

I am writing a class that implements the following method:

public void run(javax.sql.DataSource dataSource);

Within this method, I wish to

6条回答
  •  无人及你
    2020-12-24 02:54

    The second solution causes an exception because of a refresh problem. A more elegant way will be adding objects to the context and then loading xml definitions using the xmlreader. Thus:

     ObjectToBeAddedDynamically objectInst = new ObjectToBeAddedDynamically();
      DefaultListableBeanFactory parentBeanFactory = new DefaultListableBeanFactory();  
      parentBeanFactory.registerSingleton("parameterObject", objectInst);
    
      GenericApplicationContext parentContext = new GenericApplicationContext(parentBeanFactory);
    
      XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(parentContext);
       xmlReader.loadBeanDefinitions(new FileSystemResource("beandefinitions.xml"));
       parentContext.refresh();
    
       ObjectUsingDynamicallyAddedObject userObjectInst= (ObjectUsingDynamicallyAddedObject )parentContext.getBean("userObject");
    

    and

        
        
    
        
          
    
    
    
    
    

    works perfect!

提交回复
热议问题