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?
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.
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 .
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.
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.
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