开发者

Can Spring's ObjectFactoryCreatingFactoryBean work with generics that refer to interfaces?

I'm using Spring's ObjectFactoryCreatingFactoryBean to retrieve a prototype scoped bean, as described in the Spring Documentation. Below is my applicationContext.

<bean id="exportFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
    <property name="targetBeanName">
        <idref local="export" />
    </property>
</bean>

<bean id="export" class="com.someorg.ExportImpl" scope="prototype"/>

I autowire the exportFactory into a class like so:

@Autowired
@Qualifier("exportFactory")
private ObjectFactory<?> exportFactory;

And this works as expected. Each call to the exportFactory.getObject() method returns a new ExportImpl. On further inspect, a call to getObject() actually returns the following instance: org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean$TargetBeanObjectFactory

Now, ExportImpl is an implementation of an Export interface. And when I attempt to to declare the exportFactory using generics, described below, I get an exception.

@Autowired
@Qualifier("exportFactory")
private ObjectFactory<Export> exportFactory;

Stacktrace:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.someorg.Export] 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), @org.springframework.beans.factory.annotation.Qualifier(value=exportFactory)}

The application context successfully loads with this configuration, and the exception is thrown when I call exportFactory.getObject(). Using the same configuration I开发者_运维技巧 can successfully retrieve an instance of ExportImpl, so I know that bean is correctly wired.

I'd like to know a) what is Spring doing here and b) is there a reason I'm unable to use an ObjectFactory with type parameter that's an interface?


It turns out that ObjectFactoryCreatingFactoryBean is not necessary when you obtain ObjectFactory via @Autowired. In this case ObjectFactory for your bean is created automatically, though I can't find any reference of this behaviour in the documentation.

So, the behaviour you observe can be explained as follows:

  • When you write @Autowired @Qualifier("exportFactory") ObjectFactory<?>, Spring creates ObjectFactory that returns a bean named exportFactory, which itself is an ObjectFactory returned by the ObjectFactoryCreatingFactoryBean (its class is org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean$TargetBeanObjectFactory).

  • When you write @Autowired @Qualifier("exportFactory") ObjectFactory<Export>, Spring tries to find bean of type Export named exportFactory, and the search fails.


Change the qualifier to:

@Qualifier("export")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜