将豆子注入枚举

我有DataPrepareService,它为报告准备数据,我有一个包含报告类型的枚举,我需要将ReportService注入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;

,但它不起作用

如何将我的服务注入枚举?


答案 1
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的答案是有效的,如果你把内部类改为静态,这样春天就能看到它


答案 2

也许是这样的:

public enum ReportType {
    @Component
    public 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"),
    ...
}

推荐