使用spring注释将值注入到地图中
我在用spring。 大多数情况下,我会注入组件和服务。 但是现在我想用枚举键初始化一个映射并注入“Cache”实现的值,这样在给定枚举的情况下我可以让对象刷新缓存。
Map Key Value "category" @Inject Category "attr" @Inject Attr "country" @Inject Country
我的class级就像
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(像bellow或链接 )完成,但我想用注释来完成。
如果Spring上下文中有以下bean:
@Component("category") class Category extends Cache { } @Component("attr") class Attr extends Cache { } @Component("country") class Country extends Cache { }
请注意,不需要将范围显式设置为单例,因为这是Spring中的默认值。 此外,没有必要使用@Qualifier
; 它足以通过@Component("beanName")
设置bean名称。
将单例bean实例注入地图的最简单方法如下:
@Autowired Map map;
这将有效地将所有Cache
子类自动assembly到地图中,其中键是bean名称。
您可以使用Spring Expression Language完成此操作。
我已经改变了你的下面的地图定义:
以注释为基础。 以下是代码:
PersonBean
@Component("PersonBean") public class PersonBean { public String getMessage() { return "hello!"; } }
人
package com.mkyong.common; public class Person { private String name; private String address; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
PersonConfiguration
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mkyong.common.Person; @Configuration public class PersonConfiguration { @Bean public Person person() { Person person = new Person(); person.setName("mkyongMap"); person.setAddress("address"); person.setAge(28); return person; } }
的TestController
import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.mkyong.common.Person; @Controller public class TestController { @Value("#{{'Key 1':1, 'Key 2':@PersonBean, 'Key 3': @person}}") Map testMap; @RequestMapping("/test") public void testMethod() { System.out.println(testMap.get("Key 1")); PersonBean personBean = (PersonBean) testMap.get("Key 2"); System.out.println(personBean.getMessage()); Person person = (Person) testMap.get("Key 3"); System.out.println("Name: " + person.getName() + ", Address: " + person.getAddress() + ", Age: " + person.getAge()); } }