Spring怎样在一个bean里反复生成另一个bean的新实例

在说到prototype是,有可能我们就会引现出一个需求,这个需求就是,我能不能在一个bean里,在需要的情况下每次都能产生一个新的prototypebean。基本的特性是不能满足这个需求的。比如你把bean Ascope定义为prototype,注入bean B, 只有在注入的这一刻有新的bean A生成,在beanB内部执行的过程中是不会新生成Bean A的。那么有没有办法满足这一需求?答案是肯定。最不友好的一种方式是使bean B实现接口ApplicationContextAware,这样在Bean B里就可以访问ApplicationContext,这样就可以显式调用getBean来每次生成新的Bean A。但这种方式使spring的类***了Bean B,不是优雅的方式。有没有更优雅的反方式?大事是有。我们可以用Method Injection。例子如下:

XML-Based

package fiona.apple;

// no more Spring imports!

publicabstractclass CommandManager {

public Object process(ObjectcommandState) {
       
// grab a new instance ofthe appropriate Command interface
        Command command =createCommand();
       
// set the state on the(hopefully brand new) Command instance
       command.setState(commandState);
       
returncommand.execute();
    }

//okay... but where is the implementation of this method?
   
protectedabstract CommandcreateCommand();
}

 

From<https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-method-injection>

 

<!-- a statefulbean deployed as a prototype (non-singleton) -->
<beanid="myCommand"class="fiona.apple.AsyncCommand"scope="prototype">
   
<!-- inject dependencies here as required-->
</bean>

<!--commandProcessor uses statefulCommandHelper -->
<beanid="commandManager"class="fiona.apple.CommandManager">
   
<lookup-methodname="createCommand"bean="myCommand"/>
</bean>

 

From<https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-method-injection>

 

Annotation-Based

publicabstractclassCommandManager {

public Object process(ObjectcommandState) {
        Command command =createCommand();
       command.setState(commandState);
       
returncommand.execute();
    }

@Lookup("myCommand")
   
protectedabstract CommandcreateCommand();
}

 

From<https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-method-injection>

 

 

 

 

这样每次调用createCommand,就有新的Command生成。

 

Method InjectionMethod 应该满足如下形式:

<public|protected> [abstract] <return-type> theMethodName(no-arguments);

 

From<https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-method-injection>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章