Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring Map not working as expected

I'm using Spring 3.0.4. I have some beans that use the @Autowired annotation on Maps. These maps are defined within an application-context.xml file (as these maps are constructed using several factory methods).

When I use my debugger, I can see the map gets constructed using the properly (expected) bean id. However, once the autowiring process starts, it claims it cannot find a bean with the id that just has been created.

Piece of code:

@Autowired
@Qualifier("dienstverbandMap")
private Map<String, String> dienstverbandMap;

Piece of context xml:

<bean class="java.util.HashMap" id="dienstverbandMap" factory-bean="someFactoryMethod" factory-method="getMappedMap"/>  

Important detail, when I change the type to java.lang.Object in both my Class and the context xml it does get wired In fact, I can cast it to a HashMap in my code and get everything to work. But that is not what i want obviously.

Anyone got an explantion what I'm doing wrong?

like image 795
Stefan Hendriks Avatar asked Feb 09 '11 09:02

Stefan Hendriks


People also ask

Why Autowiring is not working?

When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.

What will happen if I make @autowired as false?

By default, the @Autowired annotation implies that the dependency is required. This means an exception will be thrown when a dependency is not resolved. You can override that default behavior using the (required=false) option with @Autowired .

What is Autodetect mode of Autowiring?

Q 37 - What is autodetect mode of autowiring? A - Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.


1 Answers

3.11.3. Fine-tuning annotation-based autowiring with qualifiers:

Quote: If you intend to express annotation-driven injection by name, do not primarily use @Autowired - even if is technically capable of referring to a bean name through @Qualifier values. Instead, prefer the JSR-250 @Resource annotation which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

As a specific consequence of this semantic difference, beans which are themselves defined as a collection or map type cannot be injected via @Autowired since type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection/map bean by unique name.

like image 193
Erhan Bagdemir Avatar answered Oct 05 '22 04:10

Erhan Bagdemir