我正面临Spring-DM和@Autowired Osgi Services的问题。 我已经定义了一个Spring bean + OSGI服务如下:
<bean id="my.sessionFactoryBean"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref local="my.dataSource" />
</property>
...
</bean>
<osgi:service ref="my.sessionFactoryBean"
id="my.sessionFactory" interface="org.hibernate.SessionFactory" />
我可以从另一个捆绑包中引用此服务,而不会出现如下所示的xml bean定义中的任何问题:
<beans>
...
<osgi:reference id="my.sessionFactory"
interface="org.hibernate.SessionFactory" />
..
<bean id="my.databaseItemReader"
class="my.MyReader">
<property name="sessionFactory" ref="my.sessionFactory" />
...
</beans>
我的问题依赖于使用@Autowired anotation,如下所示:
public abstract class AbstractHibernateDao {
@Autowired
@Qualifier(value="my.sessionFactory")
private SessionFactory sessionFactory;
...
我收到了经典错误:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.Sess
ionFactory my.AbstractHibernateDao.sessionFactory; nested exception is org.springfr
amework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for d
ependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {
@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qu
alifier(value=my.sessionFactory)}
如果删除@Qualifier,我会收到此错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: [my.sessionFactoryBean, my.sessionFactory]
这让我觉得我在Spring bean注册表中有我的OSGI-Service ... 我有什么想法吗?
仅供参考,我还尝试在setter上使用@ServiceReference注入OSGI服务,但是Spring-DM从不注入它(有一些nullpointerexception)
答案 0 :(得分:0)
只是猜测,但是当你使用@Autowire时,你必须做“上下文:组件扫描”,而这反过来可能会找到正在显示的额外bean(my.sessionFactoryBean)。使用XML注入时,可能未启用组件扫描,因此OSGi服务已正确解析。