Inject bean into enum

前端 未结 8 2028
误落风尘
误落风尘 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 03:00

    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.

    0 讨论(0)
  • 2020-11-30 03:03
    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

    0 讨论(0)
提交回复
热议问题