Spring 自动装配和原型范围 [英] Spring autowire and prototype scope

查看:33
本文介绍了Spring 自动装配和原型范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Bar 的类,带有以下注释:@Configurable(autowire = Autowire.BY_TYPE)

I have a class named Bar with the following annotation: @Configurable(autowire = Autowire.BY_TYPE)

在私人成员上,我有以下注释:

On a private member I have the following annotation:

@Autowired(required = true)
private Foo foo;

在 spring 配置中,我有一个 Foo 类的 bean.如果 bean 是用 scope="prototype" 定义的,它就不起作用,我得到以下异常:

In the spring configuration I have a bean of class Foo. If the bean is defined with scope="prototype" it doesn't work and I get the following exception:

NoSuchBeanDefinitionException: 没有找到匹配的 Foo 类型的依赖项:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选

NoSuchBeanDefinitionException: No matching bean of type Foo found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency

一旦我将注入的 bean 范围更改为 "singleton",它就可以正常工作.

Once I change the injected bean scope to "singleton" it works fine.

是否允许原型作用域 bean 的自动连接?

Isn't auto wiring of prototype scoped bean allowed?

是否有任何解决方法(除了手动获取 bean)?

Is there any workaround (beside getting the bean manually)?

提前致谢,阿夫纳

推荐答案

以下链接为此类场景提供了替代解决方案:http:///whyjava.wordpress.com/2010/10/30/spring-scoped-proxy-beans-an-alternative-to-method-injection/

The following link provide alternative solutions for such scenarios: http://whyjava.wordpress.com/2010/10/30/spring-scoped-proxy-beans-an-alternative-to-method-injection/

链接谈到添加到 Foo:

The link talks about adding to Foo:

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
class Foo

这将导致每次调用都有一个新实例.

Which will cause a new instance for every call.

这篇关于Spring 自动装配和原型范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆