Issue
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"/>
Solution
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);
}
}
}
Answered By - Ittai
Answer Checked By - Willingham (JavaFixing Volunteer)