Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can spring @Autowired Map?

Here's the Map

@Autowired private Map<String, ISendableConverter> converters; 

and ISendableConverter

public interface ISendableConverter {      ISendableMsg convert(BaseMessage baseMessage);      String getType(); } 

There are some classes that implements ISendableConverter

I want to inject them into the variable converters by using spring @Autowried annotation.

The instance of class as value, and the result of method getType() as key.

like this one

@Component public class SendableVoiceMsgConverter implements ISendableConverter {      @Override     public ISendableMsg convert(BaseMessage baseMessage) {         // TODO Auto-generated method stub         return null;     }      @Override     public String getType() {         return "VOICE";     } } 

Is this possible? and how?

like image 605
Joe Avatar asked Jan 04 '14 08:01

Joe


People also ask

Can we Autowire map in spring?

No, you can't inject them into a Map where the key is the return value of a method call on a bean.

What does @autowired spring do?

Overview. Starting with Spring 2.5, the framework introduced annotations-driven Dependency Injection. The main annotation of this feature is @Autowired. It allows Spring to resolve and inject collaborating beans into our bean.

Can we use @autowired for interface?

If you try to use @Autowired on an interface, the Spring framework would throw an exception as it won't be able to decide which implementation class to use.


1 Answers

Try with something like @Resource - I have not tested this code.

@Resource(name="converters") private Map<String, ISendableConverter> converters; 

or

@Value("#{converters}") private Map<String, ISendableConverter> converters; 

From Spring Docs

(..) beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.

This should work, only if you prepare converters bean like this:

<util:map id="converters" scope="prototype" map-class="java.util.HashMap"            key-type="java.lang.String" value-type="...ISendableConverter">     <entry key="VOICE" value="sendableVoiceMsgConverter" /> </util:map> 

This is also similar question:

  • Auto-wiring a List using util schema gives NoSuchBeanDefinitionException
  • Spring can't autowire Map bean
like image 149
MariuszS Avatar answered Sep 23 '22 15:09

MariuszS