自动装配工厂创建的实例的 Spring 方法是什么?
我有一个控制器,它应该创建版本相关的实例(当前未实现)。
@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 注释)未设置。 我该怎么办,FactoryBean 是要实现的正确接口吗?
我更喜欢一个不涉及 xml 配置的解决方案。
组件本身:
ReportComp implements I_Report {
@Autowired
private ReportDao reportDao;
^^^^^^^<- not set after creation
...
}
}
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
...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您创建对象,Spring 不会执行自动装配。这里有几个选项
prototype
范围 - 这将使工厂变得多余(这适用于您只想在工厂中实例化的情况)ReportDao
在工厂中,并通过 setter 将其设置为ReportComp
ApplicationContext
并执行ctx.getAutowireCapableBeanFactory().autowireBean(实例)
Spring doesn't perform autowiring if you create your objects. Here are a few options
prototype
- this will make the factory redundant (this is applicable in case you simply want instantiation in the factory)ReportDao
in the factory, and set it to theReportComp
via a setterApplicationContext
in the factory and doctx.getAutowireCapableBeanFactory().autowireBean(instance)