Alex Rivera | Logout

How to get beans created by FactoryBean spring managed?

Asked 2011-02-11T14:44:19.650
34

The FactoryBean can be used to programmatically create objects which might require complex instantiation logic.

However, it seems that the beans created by the FactoryBean doesn't become spring managed. Is this interpretation correct? If so, are there any nice workarounds? A short code sample is included to illustrate my problem.

ApplicationContext:

<bean id="searcher" class="some.package.SearcherFactory" /> 
<bean id="service" class="some.package.Service" /> 

Factory implementation:

public class SearcherFactory implements FactoryBean<Searcher> {

    @Override
    public Searcher getObject() throws Exception {
        return new Searcher(); // not so complex after all ;)
    }

    @Override
    public Class<Searcher> getObjectType() {
        return Searcher.class;
    }
    .... 
}

Class created by the factory:

public class Searcher() {
      private Service service;

      @Autowired
      public void setService(Service service) {
           // never invoked
           this.service=service;
      } 
}
Edit
Report

1 Answer

4

A manual way would be:

  1. Inject the dependencies in the factory bean
  2. set them manually on the target object.

You can also inject ApplicationContext in the factory bean (or get it by implementing ApplicationContextAware), and do ctx.getAutowireCapableBeanFactory().autowireBean(bean)

I admit both feel strange, though.

But in fact, if the logic is that simple (only instantiation), use prototype scope.

answered 2011-02-11T14:50:58.463

Your Answer