Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifing the keys of a map when autowiring in spring

Can I specify for spring how to set the key of a map when it is autowired?

In the following example I would like to somehow let spring know that the returned value of the beans' getKey() should act as key for the autowired map of the 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"/>
like image 510
Ittai Avatar asked Jan 01 '26 05:01

Ittai


2 Answers

One can rewrite MapHolder in such a way to allow the map to be filled at bean construction.

@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);
        }
    }
}
like image 187
Ittai Avatar answered Jan 03 '26 22:01

Ittai


I used @Qualifier annotation:

@Component
public MapHolder {
   @Autowire
   @Qualifier("mapName")
   private Map<Integer, MyInterface> myAutowireMap;

   public mapHolder() {
   }
}

And bean creation:

@Configuration
class MyConfig {
    @Bean
    @Qualifier("mapName")
    public Map<Integer, MyInterface> mapBean(List<MyInterface> myAutowireList){
        for(MyInterface ob : myAutowireList){
            myAutowireMap.put(ob.getKey(),ob);
        }
    }
}
like image 24
Georgii Goriachev Avatar answered Jan 03 '26 21:01

Georgii Goriachev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!