【问题标题】:Specifing the keys of a map when autowiring in spring在春季自动装配时指定地图的键
【发布时间】:2016-06-03 12:42:55
【问题描述】:

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

【问题讨论】:

    标签: java spring spring-mvc dictionary autowired


    【解决方案1】:

    可以重写 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】:

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

    【讨论】:

      【解决方案3】:

      您也可以在注解中为组件/服务赋值。这个值将被 spring 用作 bean 映射的键。

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

      【讨论】:

        猜你喜欢
        • 2015-01-24
        • 2019-08-02
        • 2017-12-13
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        相关资源
        最近更新 更多