What is the spring way to autowire factory created instances?

↘锁芯ラ 提交于 2019-12-18 13:37:06

问题


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
    ...
    }

}

回答1:


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)


来源:https://stackoverflow.com/questions/6596655/what-is-the-spring-way-to-autowire-factory-created-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!