I have a situation where adding the @Autowired
annotation gives me the following error:
Field myMap in my.package.MyClassA required a bean of type 'java.lang.String' that could not be found.
However, if I remove the annotation it works normally and the map is initialized. Here is how my code looks like:
MyClassA.java
public class MyClassA {
private static int maxRetry;
@Autowired
private Map<String, String> myMap;
/* Setters and Getters */
}
MyClassB.java
public class MyClassB {
@Autowired
private MyClassA myClassA;
/* Do something with myClassA */
}
bean-config.xml
<bean id="myMapBean" class="java.util.HashMap" scope="singleton">
<constructor-arg>
<map>
<entry key="R01" value="A" />
<entry key="R02" value="B" />
</map>
</constructor-arg>
</bean>
<bean id="myClassA" class="my.package.MyClassA">
<property name="maxRetry">
<value>10</value>
</property>
<property name="myMap" ref="myMapBean" />
</bean>
I have tried using the util:map
but I get the exact same result.
Another solution I tried was setting the map as a static field (like some other fields in the class) and take out the annotation since I have read that @Autowired
doesn't work with static fields, but if I don't autowire private MyClassA myClassA
the static fields don't initialize with the value set in the xml. Tried using @Component
on MyClassA
but that doesn't fix the issue either.
Am I doing something wrong or am I using @Autowired
incorrectly and what would be the best way to fix this? I used another project I have at hand that also uses this mapping structure and the annotation works without flaws on that project.