Spring Java Configuration - 如何为bean-references创建枚举映射 [英] Spring Java Configuration - how do create a map of enums to beans-references

查看:100
本文介绍了Spring Java Configuration - 如何为bean-references创建枚举映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用基于Java的配置,我试图将枚举映射到bean引用的映射转换为纯java配置(目前在XML和工作中),但似乎无法在文档中找到任何内容;

with Java based configuration, i am trying to convert a map that maps enums to bean references to be in pure java config (currently in XML & works) but can't seem to find anything in the documentations;

目前,我的XML就是这样;

Currently, my XML like so;

<util:map id="colourHanders" key-type="com.example.ColourEnum"
          value-type="com.example.ColourHandler">
    <entry key="white" value-ref="whiteColourHandler"/>
    <entry key="blue" value-ref="blueColourHandler"/>
    <entry key="red" value-ref="redColourHandler"/>
</util:map>

我很确定这很容易但又找不到任何关于如何的主题在Pure Java中表示这一点(所以我没有任何XML配置文件)..

I'm sure it is easy but again, can't find anything on the subject of how to represent this in Pure Java (so I don't have any XML configuration files)..

注意;使用@Component注释创建 ColourHandler bean,例如。

Note; the ColourHandler beans are created using the @Component annotation, e.g..

@Component
public class RedColourHandler implements ColourHander{
.....
}

并且colourHandlers的地图被引用为;

and the map of colourHandlers is referenced as so;

@Resource(name="colourHandlers")
    private Map<ColourHandlerEnum, ColourHandler> colourHandlers;

谢谢,

伊恩。

推荐答案

你可能想要这样的东西:

You probably want something like this:

@Configuration
public class MyConfiguration {
    @Bean public Map<ColourEnum, ColourHandler> colourHandlers() {
        Map<ColourEnum, ColourHandler> map = new EnumMap<>();
        map.put(WHITE, whiteHandler());
        // etc
        return map;
    }

    @Bean public ColourHandler whiteHandler() {
        return new WhiteHandler();
    }
}

如果您需要将处理程序保持为 @Component s,然后你可以将它们自动装入配置类:

If you need to keep your handlers as @Components, then you can autowire them into the configuration class:

@Configuration
public class MyConfiguration {
    @Autowired private WhiteColourHandler whiteColourHandler;

    @Bean public Map<ColourEnum, ColourHandler> colourHandlers() {
        Map<ColourEnum, ColourHandler> map = new EnumMap<>();
        map.put(WHITE, whiteColourHandler);
        return map;
    }
}

这篇关于Spring Java Configuration - 如何为bean-references创建枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆