Inject bean into enum

Andrej Soroj picture Andrej Soroj · May 1, 2013 · Viewed 38.9k times · Source

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?

Answer

user3195004 picture user3195004 · Jan 14, 2014
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 works if you change inner class to static so spring can see it