Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the spring way to autowire factory created instances?

I have a controller which is supposed to create version dependend instances (currently not implemented).

@Controller
public class ReportController {

    @Autowired
    private ReportCompFactory       reportCompFactory;

         public ModelAndView getReport() {
            I_Report report = reportCompFactory.getObject();
                      ^^^^^<- no autowiring in this instance 
         }
     ...
}

The Factory looks like this:

@Component
public class ReportCompFactory implements FactoryBean<I_Report> {

    @Override
    public I_Report getObject() throws BeansException {
        return new ReportComp();
    }

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

    @Override
    public boolean isSingleton() {
        return false;
    }
}

The created instances fields (@Autowired annotated ) are not set. What should I do, is FactoryBean the right interface to implement?

I would prefer a solution which doesn't involve xml-configurations.

The component itself:

    ReportComp implements I_Report {

        @Autowired
        private ReportDao           reportDao;
                                     ^^^^^^^<- not set after creation
    ...
    }

}
like image 348
stacker Avatar asked Feb 24 '23 16:02

stacker


1 Answers

Spring doesn't perform autowiring if you create your objects. Here are a few options

  • define the bean to be of scope prototype - this will make the factory redundant (this is applicable in case you simply want instantiation in the factory)
  • inject the ReportDao in the factory, and set it to the ReportComp via a setter
  • inject ApplicationContext in the factory and do ctx.getAutowireCapableBeanFactory().autowireBean(instance)
like image 136
Bozho Avatar answered Feb 26 '23 04:02

Bozho