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

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

本文介绍了自动装配工厂创建的实例的弹簧方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器应该创建版本依赖实例(目前尚未实现)。

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

工厂看起来像这样:

@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;
    }
}

创建的实例字段(@Autowired annotated)不是组。
我该怎么办,FactoryBean是实现的正确接口吗?

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

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

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

组件本身:

    ReportComp implements I_Report {

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

}


推荐答案

如果您创建对象,Spring不会执行自动装配。以下是几个选项

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


  • 将bean定义为范围 prototype - 这个将使工厂多余(这适用于您只是想在工厂实例化)

  • 在工厂注入 ReportDao ,并通过setter

  • 注入 ApplicationContext 将其设置为 ReportComp 出厂并执行 ctx.getAutowireCapableBeanFactory()。autowireBean(instance)

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

这篇关于自动装配工厂创建的实例的弹簧方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:31