java—将Springbean注入enum并在enum函数接口内调用它

atmip9wb  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(463)

好吧,我想我正在努力实现更多,但我想为我的应用程序中的所有字典值创建一个聚合器类。因此,我创建了一个枚举,它将有两个参数-第一个是字典名,第二个是 Supplier . 我去了 Supplier 因为为每个字典提供的值的计算方式不同。到目前为止我想到了这个:

public enum DictionaryAggregator {

    STATUS_X("statusX", StatusX::getDictionary),
    STATUS_Y("statusY", new Supplier<Map<String, ?>>() {
        @Override
        public Map<String, ?> get() {
            return <would like to reference to statusYCache which is inside DictionaryAggregatorServiceInjector>;
        }
    });

    private final String dictionaryName;
    private final Supplier<Map<String, ?>> dictionary;

    public String getDictionaryName() {
        return dictionaryName;
    }

    public Supplier<Map<String, ?>> getDictionary() {
        return dictionary;
    }

    DictionaryAggregator(String dictionaryName, Supplier<Map<String, ?>> dictionary) {
        this.dictionaryName = dictionaryName;
        this.dictionary = dictionary;
    }

    @Component
    static class DictionaryAggregatorServiceInjector {

        @Autowired
        private StatusYService statusYService;

    }
}

但无论我尝试了什么,我都想不出一个办法,我怎么能从中提供价值呢 StatusYCache 服务。理想情况下,我想实现的是 Supplier 为了 STATUS_Y 可以很容易地从 StatusYService .

d6kp6zgx

d6kp6zgx1#

我想我应该多用脑子。我想到了这个:

public enum DictionaryAggregator {

    STATUS_X("statusX", StatusX::getDictionary),
    STATUS_Y("statusY", new Supplier<Map<String, ?>>() {
        @Override
        public Map<String, ?> get() {
            return new StatusYDictionaryClass(DictionaryAggregatorServiceInjector.shipmentStatusVos).getDictionary();
        }
    });

    private final String dictionaryName;
    private final Supplier<Map<String, ?>> dictionary;

    public String getDictionaryName() {
        return dictionaryName;
    }

    public Supplier<Map<String, ?>> getDictionary() {
        return dictionary;
    }

    DictionaryAggregator(String dictionaryName, Supplier<Map<String, ?>> dictionary) {
        this.dictionaryName = dictionaryName;
        this.dictionary = dictionary;
    }

    @Component
    static class DictionaryAggregatorServiceInjector {

        static List<StatusYObj> statusYList;

        @Autowired
        public StatusYService statusYService;

        @PostConstruct
        public void init() {
            statusYList = statusYService.getStatusYList();
        }

    }
}

它似乎起作用了。

相关问题