我在使用此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)}
如果我删除了自动连接类的 extends ThreadProvider ,我看到我没有收到此错误,但我确实需要ThreadProvider抽象类。
答案 0 :(得分:19)
如果ThreadProvider层次结构中的任何地方都有接口,请尝试将接口的名称作为服务提供者的类型,例如。如果你说这个结构:
public class ThreadProvider implements CustomInterface{
...
}
然后在你的控制器中试试这个:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
发生这种情况的原因是,在你第一种情况下你没有ChiusuraProvider
扩展ThreadProvider
Spring可能是为你创建一个基于CGLIB的代理(处理@Transaction)。
当DID从ThreadProvider
扩展时假设ThreadProvider扩展了某个接口,那么Spring会创建一个基于Java动态代理的代理,它似乎是该接口的实现,而不是{{1} } type。
如果您绝对需要使用ChisuraProvider
,您可以尝试使用AspectJ作为替代方法,或者使用ThreadProvider强制使用基于CGLIB的代理:
ChisuraProvider
以下是Spring Reference网站上的更多参考资料:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
答案 1 :(得分:7)
您应该将此行放在应用程序上下文中:
<context:component-scan base-package="com.cinebot.service" />
Read more about Automatically detecting classes and registering bean definitions in documentation