Spring踩坑-No qualifying bean of type

242 阅读1分钟

背景

在开发中,发现服务启动时报错:

 [WARN] ClassPathXmlApplicationContext  (AbstractApplicationContext.java:551) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appService': Unsatisfied dependency expressed through field 'remittanceService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.aaa.RemittanceService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

报错提示在装配Bean的时候找不到'com.aaa.RemittanceService'这个类,但是这个类确实使用了@Service注解。

原因

按理说使用了@Service注解Spring会对Bean进行装载,排除了import导入问题,发现在xml中也配置了一个Bean,这个Bean的id和com.aaa.RemittanceService的name是一样的,因此xml配置的Bean会覆盖掉@Service注解装配的Bean。所以,只需要改RemittanceService的名字或者改xml中id即可。

<bean id="remittanceService" class="com.proxy.ServerPublisher"  
init-method="publish" destroy-method="destroy">   
</bean>