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"/>
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);
}
}
}
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With