Inject bean into enum

前端 未结 8 2033
误落风尘
误落风尘 2020-11-30 02:01

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 ReportServic

8条回答
  •  失恋的感觉
    2020-11-30 02:48

    Enums 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 the ApplicationContextAware interface.

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class ApplicationContextProvider implements ApplicationContextAware{
    
     private static ApplicationContext appContext = null;
    
     public static ApplicationContext getApplicationContext() {
       return appContext;
     }
    
     public void setApplicationContext(ApplicationContext appContext) throws BeansException {
       this.appContext = appContext;
     }
    }
    

    then add this your application context file:

    
    

    after that you could access to the application context in a static way like this:

    ApplicationContext appContext = ApplicationContextProvider.getApplicationContext();
    

提交回复
热议问题