我有一个使用Spring MVC开发的Web应用程序。此应用程序必须使用具有Spring注释的库中的bean:
@Service
public class DefaultSampleService implements SampleService {
@Autowired SampleRepository sampleRepository;
//Methods of service
}
我无法在我的应用程序中扫描这个bean所以,尽管有Spring注释,我必须通过库提供的工厂来实例化这个bean。
<beans>
<bean id="libraryFactory" class="com.company.LibraryFactory" />
<bean id="sampleService" factory-bean="libraryFactory" factory-method="getSampleService" />
</beans>
工厂返回一个sampleService bean,其中填充了sampleRepository属性。但是,当应用程序加载xml配置时,我得到一个NoSuchBeanDefinitionException,因为Spring没有找到SampleRepository的bean。
确实,Spring的beanFactory中没有SampleRepository bean。但我不需要它,因为sampleService由工厂实例化并且其属性被填充。
如何使用sampleService bean阻止自动装配过程?
我尝试将属性autowire =“no”添加到sampleService定义中,但它不起作用。
<bean id="sampleService" factory-bean="libraryFactory" factory-method="getSampleService" autowire="no" />
这是堆栈跟踪:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.company.lib.repositories.SampleRepository com.company.lib.services.DefaultSampleService.sampleRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.lib.repositories.SampleRepository] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 54 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.lib.repositories.SampleRepository] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 56 more