使用Spring注释将值注入地图


问题内容

我正在用弹簧。通常,我将注入组件和服务。但是,现在我想用枚举键和注入“ 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来完成(例如波纹管或在link处),但是我想通过注释来完成。

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

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

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

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

注意,不需要将范围显式设置为单例,因为这是Spring的默认设置。此外,无需使用@Qualifier;通过设置bean名称就足够了@Component("beanName")

将单例bean实例注入到映射的最简单方法如下:

@Autowired
Map<String, Cache> map;

这将有效地将的所有子类自动关联Cache到地图,键为bean名称。