Java 在spring中自动关联时指定贴图的键

Java 在spring中自动关联时指定贴图的键,java,spring,spring-mvc,dictionary,autowired,Java,Spring,Spring Mvc,Dictionary,Autowired,我可以为spring指定在地图自动连线时如何设置其关键点吗 在下面的示例中,我想让spring知道bean的getKey()的返回值应该作为mapHolder bean的自动连线映射的键 public interface MyInterface{ int getKey(); } @Component public ImplA implements MyInterface{ @Override public int getKey(){ return 1;

我可以为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"/>
公共接口MyInterface{
int getKey();
}
@组成部分
公共ImplA实现了MyInterface{
@凌驾
public int getKey(){
返回1;
}
}
@组成部分
公共ImplB实现了MyInterface{
@凌驾
public int getKey(){
返回2;
}
}
@组成部分
公众地图持有人{
@自动连线
私有地图myAutowiredMap;
公众地图持有人(){
}
}

可以通过这种方式重写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);
        }
    }
}
@组件
公众地图持有人{
@自动连线
私有列表myAutowireList;
私有映射myAutowireMap=新建。。。;
公众地图持有人(){
}
@施工后
公共void init(){
用于(MyInterface ob:myAutowireList){
myAutowireMap.put(ob.getKey(),ob);
}
}
}

您还可以在注释中为组件/服务分配一个值。spring将使用该值作为bean映射的键

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

我使用了
@限定符
注释:

@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);
        }
    }
}
@配置
类MyConfig{
@豆子
@限定符(“映射名”)
公共地图mapBean(列表myAutowireList){
用于(MyInterface ob:myAutowireList){
myAutowireMap.put(ob.getKey(),ob);
}
}
}

难道没有更好的方法吗?