Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject bean into enum

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?

like image 892
Andrej Soroj Avatar asked May 01 '13 12:05

Andrej Soroj


2 Answers

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

like image 133
user3195004 Avatar answered Sep 20 '22 09:09

user3195004


Maybe something like this:

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"),     ... } 
like image 28
weekens Avatar answered Sep 19 '22 09:09

weekens