使用spring注释将值注入到地图中 [英] Inject values into map using spring annotation

查看:122
本文介绍了使用spring注释将值注入到地图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用春天。大多数情况下,我会注入组件和服务。但是现在我想用枚举键初始化一个映射并注入Cache实现的值,这样给定枚举我可以让对象刷新缓存。

I am using spring. Mostly I will inject the components and services. But now I want to initialize a map with enum key and injected values of the the "Cache" implementation so that given the enum I can get the object to refresh cache.

Map<String,Cache>

Key           Value
"category"    @Inject Category     
"attr"        @Inject Attr
"country"     @Inject Country

我的班级就像

public abstract class Cache{
    refreshCache() {
      clearCache();
      createCache();
    }
    clearCache();
    createCache();
}

@Component
@Scope("singleton")
@Qualifier("category")
class Category extends Cache{}

@Component
@Scope("singleton")
@Qualifier("attr")
class Attr extends Cache{}

@Component
@Scope("singleton")
@Qualifier("country")
class Country extends Cache{}

它可以通过XML完成(如下所示,或者在链接)但我想用注释来做。

It can be done by XML (Like bellow or at link) but i want to do it with annotations.

<property name="maps">
        <map>
            <entry key="Key 1" value="1" />
            <entry key="Key 2" value-ref="PersonBean" />
            <entry key="Key 3">
                <bean class="com.mkyong.common.Person">
                    <property name="name" value="mkyongMap" />
                    <property name="address" value="address" />
                    <property name="age" value="28" />
                </bean>
            </entry>
        </map>
    </property>


推荐答案

如果在Spring上下文中有以下bean:

If you have the following beans in your Spring context:

@Component("category")
class Category extends Cache { }

@Component("attr")
class Attr extends Cache { }

@Component("country")
class Country extends Cache { }

请注意,不需要将范围显式设置为单例,因为这是Spring中的默认值。此外,没有必要使用 @Qualifier ;它足以通过 @Component(beanName)设置bean名称。

Note that there's no need to explicitly set scope to singleton, since this is the default in Spring. Besides, there's no need to use @Qualifier; it's enough to set the bean name via @Component("beanName").

最简单的注入方式单个bean实例到地图如下:

The most simple way to inject singleton bean instances to a map is as follows:

@Autowired
Map<String, Cache> map;

这将有效地自动装配 Cache 的所有子类到地图,键是豆名。

This will effectively autowire all subclasses of Cache to the map, with the key being the bean name.

这篇关于使用spring注释将值注入到地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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