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 createsObjectFactory
that returns a bean namedexportFactory
, which itself is anObjectFactory
returned by theObjectFactoryCreatingFactoryBean
(its class isorg.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean$TargetBeanObjectFactory
).When you write
@Autowired @Qualifier("exportFactory") ObjectFactory<Export>
, Spring tries to find bean of typeExport
namedexportFactory
, and the search fails.
Change the qualifier to:
@Qualifier("export")
精彩评论