Ale*_*ley 7 spring components unmanaged spring-aop autowired
我想使用@AutoWired将配置了@Component的非托管bean注入托管bean.我很确定我的配置是正确的,但由于某种原因,我一直得到例外:
No unique bean of type [foo.Baz] is defined: Unsatisfied dependency of type [class foo.Baz]: expected at least 1 matching bean
Run Code Online (Sandbox Code Playgroud)
根据错误,我猜它无法找到Baz类,但我不确定为什么.我的理解是上下文:XML配置中的spring配置元素应该允许我这样做.我还确保包含适当的jar文件(spring-weaving.jar和aspectjweaver.jar).
这是我设置的一个简单示例.
我的XML配置:
<beans ...>
...
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="foo"/>
<bean id="bar" class="foo.Bar"/>
...
</beans>
Run Code Online (Sandbox Code Playgroud)
我有一个托管bean:
package foo;
public class Bar {
@Autowired
private Baz baz;
public void setBaz(Baz baz) {
this.baz = baz;
}
...
}
Run Code Online (Sandbox Code Playgroud)
还有一个非托管bean:
package foo;
@Component
public class Baz {
...
}
Run Code Online (Sandbox Code Playgroud)
有什么我想念的吗?
编辑:日志列出了它实例化的bean,而foo.Baz不是其中之一.我不知道为什么它没有拿起@Component注释类.
Mic*_*les 11
由于Bar配置了xml,因此只能使用xml进行配置.即你不能混合它们.因此Baz上的"@Autowired"注释没有被提取(没有任何注释).只有当您在类级别添加spring注释时,spring才会侦听任何其他注释.
您需要做的是在xml中配置要按类型自动装配的bean,为该类型添加一个setter,您将实现所需的行为.
<bean id="bar" class="foo.Bar" autowire="byType"/>
Run Code Online (Sandbox Code Playgroud)
还有一件事,当你使用@Component注释bean时,它是一个Spring托管bean.仅仅因为它不是用xml创建的,并不意味着它是不受管理的.一个非管理的bean是你从春天得不到的.
Bar和Baz都是春季管理.这是您选择定义不同的机制.
在一个方面,先前的回答是不正确的.您可以自动装配使用xml配置的bean.
来自http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html中的第3.4.5节:
使用基于XML的配置元数据[2]时,可以使用元素的autowire属性为bean定义指定autowire模式.自动装配功能有五种模式.您指定每个bean的自动装配,因此可以选择要自动装配的那些.
您可以按名称,类型和构造函数进行自动装配.这里有一个粗略的例子:http://www.java2s.com/Code/Java/Spring/AutoWiring.htm
归档时间: |
|
查看次数: |
20370 次 |
最近记录: |