本文介绍了将bean注入枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有DataPrepareService准备报告的数据,我有一个报告类型的枚举,我需要注入报告服务到枚举或从枚举访问ReportService。我的服务:
@Service
public class DataPrepareService {
// my服务
}
我的枚举:
public enum ReportType {
REPORT_1(name,filename),
REPORT_2(name文件名),
REPORT_3(name,filename)
public abstract Map< String,Object> getSpecificParams();
public Map< String,Object> getCommonParams(){
//一些需要服务的代码
}
}
我试图使用
@Autowired
DataPrepareService dataPrepareService;
,但没有起作用
如何将我的服务注入到枚举中?
解决方案
public enum ReportType {
@Component
public static class ReportTypeServiceInjector {
@Autowired
private DataPrepareService dataPrepareService;
@PostConstruct
public void postConstruct(){
for(ReportType rt:EnumSet.allOf(ReportType.class))
rt.setDataPrepareService(dataPrepareService);
}
}
REPORT_1(name,filename),
REPORT_2(name,filename),
.. 。
}
如果您将内部类别更改为静态,那么春天可以看到它
I have the DataPrepareService that prepare data for reports and I have an Enum with report types, and I need to inject ReportService into Enum or have access to ReportService from enum.
my service:
@Service
public class DataPrepareService {
// my service
}
my enum:
public enum ReportType {
REPORT_1("name", "filename"),
REPORT_2("name", "filename"),
REPORT_3("name", "filename")
public abstract Map<String, Object> getSpecificParams();
public Map<String, Object> getCommonParams(){
// some code that requires service
}
}
I tried to use
@Autowired
DataPrepareService dataPrepareService;
, but it didn't work
How can I inject my service into enum?
解决方案
public enum ReportType {
@Component
public static class ReportTypeServiceInjector {
@Autowired
private DataPrepareService dataPrepareService;
@PostConstruct
public void postConstruct() {
for (ReportType rt : EnumSet.allOf(ReportType.class))
rt.setDataPrepareService(dataPrepareService);
}
}
REPORT_1("name", "filename"),
REPORT_2("name", "filename"),
...
}
weekens' answer works if you change inner class to static so spring can see it
这篇关于将bean注入枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!