Thanks Marten. My factory is actually not a FactoryBean. FactoryBean makes a bean of a known type. My factory makes multiple beans of types (specified by List of java.lang.Class) that are unknown at compile time.
BeanFactoryPostProcessor is surely more appropriate than ApplicationContextAware + @PostConstruct. But it still doesn't work after rewrite. My factory makes JDK proxy:
Code:
public <T> T getProxy(Class<T> intrfc) {
return (T) Proxy.newProxyInstance(intrfc.getClassLoader(), new Class<?>[]{intrfc}, myInvocationHandler);
}
The bean definitions:
Code:
for (Class<?> clazz : classes) {
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setFactoryBeanName(/*factory's bean name*/);
beanDefinition.setFactoryMethodName("getProxy");
ConstructorArgumentValues constArgs = new ConstructorArgumentValues();
constArgs.addIndexedArgumentValue(0, clazz);
beanDefinition.setConstructorArgumentValues(constArgs);
beanDefinition.setAutowireCandidate(true);
beanFactory.registerBeanDefinition(/*proxy's bean name*/, beanDefinition);
}
When the proxy is injected explicity (ref="myProxy"), the factory method (getProxy) is invoked. For autowiring, it is not invoked before Spring complains "no matching bean of type ...". I guess it is necessary to specify in the bean definition that the proxy is an instance of the desired interface, but I can't find the API to do so.