How to instantiate spring managed beans at runtime?

后端 未结 5 1156
野的像风
野的像风 2020-12-02 11:24

I stuck with a simple refactoring from plain java to spring. Application has a \"Container\" object which instantiates its parts at runtime. Let me explain with the code:

5条回答
  •  孤街浪徒
    2020-12-02 12:20

    You don't need the Container because all of the runtime objects should be created, held and managed by ApplicationContext. Think about a web application, they are much the same. Each request contains external data/environment info as you mentioned above. What you need is a prototype/request scoped bean like ExternalData or EnvironmentInfo which can read and hold runtime data through a static way, let's say a static factory method.

    
    
    
    
    
        
        
     
    

    If you do need a container to save the runtime objects, code should be

    class Container {
    
        List list;
        ApplicationContext context;//injected by spring if Container is not a prototype bean
    
        public void load() {// no loop inside, each time call load() will load a runtime object
            RuntimeBean bean = context.getBean(RuntimeBean.class); // see official doc
            list.add(bean);// do whatever
        }
    }
    

    Official doc Singleton beans with prototype-bean dependencies.

提交回复
热议问题