【发布时间】:2018-01-28 13:08:50
【问题描述】:
我最近学到了很多关于 Spring 的知识,我认为我可能会误解的一件事是 @Autowired 注释,尤其是在构造函数中使用它时。你看,我正在开发的应用程序是一项服务,所以基本上一切都在构造函数中初始化。唯一实际发生的用户驱动事件是重新启动服务的某些模块的按钮。这是我的主要方法:
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(MDHIS_Service.class)
.headless(false).web(false).run(args);
java.awt.EventQueue.invokeLater(() ->
{
MDHIS_Service frame = ctx.getBean(MDHIS_Service.class);
frame.setSize(1024, 768);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
这是我的主类的构造函数,基本上所有事情都发生在这里。我省略了对初始化每个模块的方法的调用以缩短它:
@Autowired
public MDHIS_Service(GlobalParamService globalParamService, LogEntryService logentryService, InterfaceService interfaceService,
ConnectionService connectionService, OutboundMessageService outboundMessageService, OutboundMessageHistoryService outboundMessageHistoryService,
InboundMessageService inboundMessageService, FacilityService facilityService, ModuleStatusService moduleStatusService,
SequenceService sequenceService)
{
this.globalParamService = globalParamService;
this.logEntryService = logentryService;
this.interfaceService = interfaceService;
this.connectionService = connectionService;
this.outboundMessageService = outboundMessageService;
this.outboundMessageHistoryService = outboundMessageHistoryService;
this.inboundMessageService = inboundMessageService;
this.facilityService = facilityService;
this.moduleStatusService = moduleStatusService;
this.sequenceService = sequenceService;
}
我的主类为每个服务都有一个私有的最终全局变量。每个模块都是一个单独的线程,我发现自己必须将这些变量传递给每个模块的构造函数,该构造函数将它们存储到它自己的私有最终变量中。我现在做事的方式@Autowired 几乎没用,因为我必须传递实例。有没有办法更好地使用@Autowired?该服务用作大型 Web 应用程序的后端,我发现自己可以更好地使用其中的注释。我对此主题进行了大量研究,并尝试了 @PostContruct 注释,但我得到的只是空服务。
任何帮助将不胜感激。
谢谢!
【问题讨论】:
-
您是否正确配置了组件扫描? docs.spring.io/spring-boot/docs/current/reference/html/…
-
我的主类是这样注释的:@SpringBootApplication(scanBasePackages = "com.mdenis.mdhis_service") 这是所有其他包和类的基础包。这会做同样的事情吗?
标签: spring spring-boot constructor null autowired