首页 > 编程语言 > 详细

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

时间:2017-02-07 16:58:43      阅读:635      评论:0      收藏:0      [点我收藏+]

在说到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>


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

原文:http://simonwzing.blog.51cto.com/3896700/1895569

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!