我有为报告准备数据的 DataPrepareService,我有一个带有报告类型的 Enum,我需要将 ReportService 注入(inject) Enum 或从 enum 访问 ReportService。
我的服务:
@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;
,但是没有用
如何将我的服务注入(inject)枚举?
最佳答案
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' answer如果您将内部类更改为静态,则可以使用,以便 spring 可以看到它
关于java - 将bean注入(inject)枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318454/