开发者

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
    publ开发者_JAVA技巧ic 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
    ...
    }

}


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜