java - 将bean注入(inject)枚举

标签 java spring dependency-injection autowired

我有为报告准备数据的 DataPrepareService,我有一个带有报告类型的 Enum,我需要将 ReportService 注入(inject) Enum 或从 enum 访问 ReportService。

我的服务:

@Service
public class DataPrepareService {
    // my service
}

我的枚举:

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
    }
}

我尝试使用

@Autowired
DataPrepareService dataPrepareService;

,但是没有用

如何将我的服务注入(inject)枚举?

最佳答案

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如果您将内部类更改为静态,则可以使用,以便 spring 可以看到它

关于java - 将bean注入(inject)枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318454/

相关文章:

java - MS-Outlook PST 文件和 MS-Outlook MSG 文件之间有什么关系?

java - Spring 依赖注入(inject)无法正常工作

javascript - AngularJS 将服务注入(inject)模块而不使用变量,因此可以缩小模块

java - Spring Boot 测试类可以重用应用程序上下文以更快地运行测试吗?

java - Selenium Webdriver FindElement() 方法不起作用(NoSuchElementException)

java - 从集合中删除不符合条件的项目

java - Android - 将数据存储在数组中

java - 如何在 Spring AOP 中停止方法执行

java - 在Web项目中哪里创建了ApplicationContext?

java - 请求将在 spring : 中转到错误的处理程序