将 bean 注入枚举 [英] Inject bean into enum
本文介绍了将 bean 注入枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有为报告准备数据的 DataPrepareService,我有一个带有报告类型的 Enum,我需要将 ReportService 注入 Enum 或从 enum 访问 ReportService.
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.
我的服务:
@Service
public class DataPrepareService {
// my service
}
我的枚举:
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
}
}
我尝试使用
@Autowired
DataPrepareService dataPrepareService;
,但是没有用
如何将我的服务注入枚举?
How can I inject my service into enum?
推荐答案
public enum ReportType {
REPORT_1("name", "filename"),
REPORT_2("name", "filename");
@Component
public static class ReportTypeServiceInjector {
@Autowired
private DataPrepareService dataPrepareService;
@PostConstruct
public void postConstruct() {
for (ReportType rt : EnumSet.allOf(ReportType.class))
rt.setDataPrepareService(dataPrepareService);
}
}
[...]
}
weekens 的答案 如果您将内部类更改为静态以便 spring 可以看到它
weekens' answer works if you change inner class to static so spring can see it
这篇关于将 bean 注入枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文