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?
Enum
s are static, so you have to figure out a way to access to the beans from a static context.You can create a class named
ApplicationContextProvider
that implements theApplicationContextAware
interface.then add this your application context file:
after that you could access to the application context in a static way like this:
weekens' answer works if you change inner class to static so spring can see it
Maybe something like this:
I think this what you need
Autowire the enum as per usual
Here is the trick, use the factory-method="valueOf" and also make sure lazy-init="false"
so the container creates the bean upfront
and you are done!
Maybe you can use this solution ;
And in another class which you need the bean of the Enum :
it will be hard to control that the spring container is already up and running at the time the enum is instantiated (if you had a variable with this type in a test-case, your container will usually not be there, even aspectj autowiring won't help there). i would recommend to just let the dataprepare-service or something give you the specific-params with a lookup-method with the enum-parameter.