spring之使用实现 ApplicationListener 的 @Autowired 注入(inject)一个 bean 不起作用

wayfarer 阅读:16 2024-11-24 20:56:43 评论:0

我有一个服务 bean(用 @Service 注释),它为扩展 ApplicationEvent 抽象类的 T 类型事件对象实现 ApplicationListener 接口(interface)。在 Spring 文档中有一个非常简单明了的例子 here

然而,当我尝试使用@Autowired 将这个 bean 注入(inject)其他 bean 时,我得到的是:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [...] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotation {@org.springframework.beans.factory.annotation.Autowired(required=true)}

如果我尝试使用类似@Resource 的东西,那么我会得到一个类转换异常(试图注入(inject)一种类型的资源但得到一个代理)。

请您参考如下方法:

If i try to use something like @Resource then i get a class cast exception (attempting to inject a resource of one type but getting a Proxy).

这听起来像是您正在尝试按类引用它,而它被连接为基于接口(interface)的 JDK 代理。

如果你有这个类:

@Service 
public class FooServiceImpl implements FooService{} 

将其连接为:

@Autowired 
private FooService fooService; 

不像:

@Autowired 
private FooServiceImpl fooService; 

引用:


标签:Spring
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号