Consider a singleton factory FooFactory, which has a getFoo method that takes a single String paramter and creates a Foo object. The Foo object gets autowired as a attribute into FooClient. All very simple and normal:
The bean myFoo contains @Autowired, @PostConstruct, and @PreDestory methods. This all works fine using the XML above and the lifecycle methods get called.Code:<context:annotation-config/> <bean name="fooFactory" class="factorytest.FooFactory"/> <bean name="myFoo" factory-bean="fooFactory" factory-method="getFoo"> <constructor-arg index="0" value="some meaningful string" /> </bean> <bean name="fooClient" class="factorytest.FooClient"/>
The question is, how can one do ALL this with annotations? Such that the XML file looks like this:
Spring of course has no problem autodiscovering FooFactory and FooClient with @Component annotations... How do you replace:Code:<context:component-scan base-package="factorytest" />
So that you can still haveCode:<bean name="myFoo" factory-bean="fooFactory" factory-method="getFoo"> <constructor-arg index="0" value="myFoo" /> </bean>
inside FooClient but without the XML definition? And still have myFoo treated as a singleton with lifecycle callbacks?Code:@Resource(name = "myFoo") private Foo myFoo;
I would essentially like to "hook into" the getBean process of BeanFactory, such that when I see a request for an instance of a Foo with the bean name "myFoo", can I create it on the fly and let the contain manage it.
I have tried marking Foo @Scope("prototype"), but then it does not get treated as a singleton and receive @PreDestory. I've also tried making FooFactory a FactoryBean, but getObject on factory bean does not take any parameters. (Any hack to pass a parameter to getObject on a FactoryBean?) I've also tried BeanFactoryPostProcessor, BeanPostProcessor, and even extending AbstractAutowireCapableBeanFactory... Nothing seems clean.
So in short, is there any way to specify creation of a bean using a factory via annotations?
Thanks
Paul


Reply With Quote
