我可以指定spring在自动装配时如何设置地图的键吗?
在下面的示例中,我想以某种方式让spring知道bean的getKey()的返回值应该作为mapHolder bean的自动装配映射的键。
public interface MyInterface{
int getKey();
}
@Component
public ImplA implements MyInterface{
@Override
public int getKey(){
return 1;
}
}
@Component
public ImplB implements MyInterface{
@Override
public int getKey(){
return 2;
}
}
@Component
public MapHolder{
@Autowire
private Map<Integer, MyInterface> myAutowiredMap;
public mapHolder(){
}
}
<context:component-scan base-package="com.myquestion">
<context:include-filter type="assignable" expression="com.myquestion.MyInterface"/>
</context:component-scan>
<bean id="mapHolder" class="com.myquestion.MapHolder"/>
答案 0 :(得分:1)
我使用了@Qualifier
注释:
@Component
public MapHolder {
@Autowire
@Qualifier("mapName")
private Map<Integer, MyInterface> myAutowireMap;
public mapHolder() {
}
}
和bean的创建:
@Configuration
class MyConfig {
@Bean
@Qualifier("mapName")
public Map<Integer, MyInterface> mapBean(List<MyInterface> myAutowireList){
for(MyInterface ob : myAutowireList){
myAutowireMap.put(ob.getKey(),ob);
}
}
}
答案 1 :(得分:0)
可以用这种方式重写MapHolder,以便在bean构造中填充地图。
@Component
public MapHolder{
@Autowire
private List<MyInterface> myAutowireList;
private Map<Integer, MyInterface> myAutowireMap = new ...;
public mapHolder(){
}
@PostConstruct
public void init(){
for(MyInterface ob : myAutowireList){
myAutowireMap.put(ob.getKey(),ob);
}
}
}
答案 2 :(得分:0)
您还可以在注释中为组件/服务分配值。春季,此值将用作您的bean映射的键。
@Component("key")
public ImplA implements MyInterface{
...