自动装配工厂创建的实例的弹簧方式是什么?

sta*_*ker 4 java spring autowired

我有一个控制器,它应该创建版本dependend实例(目前尚未实现).

@Controller
public class ReportController {

    @Autowired
    private ReportCompFactory       reportCompFactory;

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

工厂看起来像这样:

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

未设置创建的实例字段(@Autowired annotated).我该怎么办,FactoryBean是实现的正确接口吗?

我更喜欢不涉及xml配置的解决方案.

组件本身:

    ReportComp implements I_Report {

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

}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 8

如果您创建对象,Spring不会执行自动装配.这里有一些选择

  • 将bean定义为范围prototype- 这将使工厂变得多余(这适用于您只想在工厂中实例化的情况)
  • ReportDao在工厂注入,并ReportComp通过设置器将其设置为
  • 注入ApplicationContext工厂并做ctx.getAutowireCapableBeanFactory().autowireBean(instance)