Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject values into map using spring annotation

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

My class are like

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

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>
like image 299
Shivay Avatar asked Dec 24 '22 14:12

Shivay


1 Answers

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

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").

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

@Autowired
Map<String, Cache> map;

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

like image 137
fps Avatar answered Jan 06 '23 06:01

fps