您的位置:首页 > 编程语言 > Java开发

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

2017-02-07 11:49 369 查看
在说到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-Basedpackage 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-BasedpublicabstractclassCommandManager {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 Injection的Method 应该满足如下形式:<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 Method Injection