在说到prototype是,有可能我们就会引现出一个需求,这个需求就是,我能不能在一个bean里,在需要的情况下每次都能产生一个新的prototype的bean。基本的特性是不能满足这个需求的。比如你把bean A的scope定义为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();
}
<!-- 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>
Annotation-Based
publicabstractclassCommandManager {
public Object process(ObjectcommandState) {
Command command =createCommand();
command.setState(commandState);
returncommand.execute();
}
@Lookup("myCommand")
protectedabstract CommandcreateCommand();
}
这样每次调用createCommand,就有新的Command生成。
Method Injection的Method 应该满足如下形式:
<public|protected> [abstract] <return-type> theMethodName(no-arguments);
Spring怎样在一个bean里反复生成另一个bean的新实例
原文:http://simonwzing.blog.51cto.com/3896700/1895569