在 spring 中自动装配时指定映射键

Specifing the keys of a map when autowiring in spring

我可以为 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"/>

可以重写 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);
        }
    }
}

你也可以给注解中的component/service赋值。 spring 将使用此值作为您的 bean 映射的键。

@Component("key")
public ImplA implements MyInterface{
...

我使用了@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);
        }
    }
}