Spring 预计至少有 1 个 bean 有资格作为此依赖项的 Autowiring 候选者

标签 spring dependency-injection autowired

我在使用这个 Autowire 时遇到了问题:

@Controller
public class ChiusuraController {

    @Autowired
    private ChiusuraProvider chiusuraProvider;
}

用这个 bean:

@Service @Transactional
public class ChiusuraProvider extends ThreadProvider {


    public void run() {}
}

延伸

public abstract class ThreadProvider extends Thread implements InitializingBean, Runnable, DisposableBean {
...
}

我收到此错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'chiusuraController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cinebot.service.ChiusuraProvider com.cinebot.web.controller.ChiusuraController.chiusuraProvider; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.cinebot.service.ChiusuraProvider] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我看到如果我删除 Autowiring 类的extends ThreadProvider,我没有收到此错误,但我确实需要 ThreadProvider 抽象类。

最佳答案

如果 ThreadProvider 层次结构中的任何地方都有接口(interface),请尝试将接口(interface)的名称作为服务提供者的类型,例如。如果你说这个结构:

public class ThreadProvider implements CustomInterface{
...
}

然后在你的 Controller 中试试这个:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

发生这种情况的原因是,在您没有 ChiusuraProvider 扩展 ThreadProvider 的第一种情况下,Spring 可能是在为您创建一个基于 CGLIB 的代理(到处理@Transaction)。

当您从 ThreadProvider 扩展时假设 ThreadProvider 扩展了某个接口(interface),在这种情况下,Spring 会创建一个基于 Java 动态代理的代理,这似乎是该接口(interface)的实现,而不是 ChisuraProvider 类型。

如果您绝对需要使用 ChisuraProvider,您可以尝试使用 AspectJ 作为替代方案,或者在使用 ThreadProvider 的情况下强制使用基于 CGLIB 的代理:

<aop:aspectj-autoproxy proxy-target-class="true"/>

这里有更多来自 Spring Reference 站点的引用:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

关于Spring 预计至少有 1 个 bean 有资格作为此依赖项的 Autowiring 候选者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11332289/

相关文章:

maven-2 - 依赖注入(inject)在使用 Jersey 和 OpenWebBeans 的 Tomcat 7 上不起作用

java - 从另一个类调用方法时 Autowiring 组件空指针异常

java - Spring Autowire 原始 boolean 值

java - 带有 Jetty 的 AbstractAnnotationConfigDispatcherServletInitializer

java - Spring分页

java - Spring boot中ServletRegistrationBean和ControllerAdvice冲突

spring - WS-Security 不适用于 CXF

c# - 带有 DI 简单注入(inject)器的 log4net

java - 确定哪些 Spring @Value 注解注入(inject)失败

java - 使用 @Component 默认 Autowiring