@Autowired and @Resource in Spring

The @Autowired annotation is used to configure the dependency injection in Spring and is associated with a setter method, or a field or a constructor of a class.
In the case of a setter method or a field the bean used for dependency injection is chosen depending on the type.
Look the following example:

  1. create a java project in your development IDE (eclipse, netbeans, etc.)
  2. configure the project in Maven with the file pom.xml

    otherwise you can use the following libraries:

    • spring-context-3.1.2.RELEASE.jar
    • spring-aop-3.1.2.RELEASE.jar
    • aopalliance-1.0.jar
    • spring-beans-3.1.2.RELEASE.jar
    • spring-core-3.1.2.RELEASE.jar
    • commons-logging-1.1.1.jar
    • spring-expression-3.1.2.RELEASE.jar
    • spring-asm-3.1.2.RELEASE.jar
    • log4j-1.2.17.jar
  3. create the folder “conf” and insert in the classpath
  4. create the file conf/app-context.xml
  5. create the file conf/log4j.xml
  6. create the file eu/lucazanini/autowired/
  7. create the file eu/lucazanini/autowired/
  8. create the file eu/lucazanini/autowired/

In this example @Autowired is used to inject the dependency with class = “eu.lucazanini.autowired.SimpleProperty” in SimpleBean, with a bean that is an instance of the PropertyBean class which is the one used by the setter method “setProperty” in SimpleBean.
@Autowired can have the attribute “required” set to true or false:

The default value for “required” is true.
When Spring is not able to determine the dependency, you get an exception if you don’t set “required” to false.
Now consider the example above after replacing the file conf/app-context.xml

where you added the bean simplePropertyTwo of the same class of the bean simplePropertyOne already present.
Now you get the exception:

It is obvious that the error is due to the ambiguity in determining which instance of the class SimpleProperty must be injected as a dependency in SimpleBean (simplePropertyOne or simplePropertyTwo).
To avoid this error you can use the annotation @Qualifier specifying the id of the right bean in eu/lucazanini/autowired/

You can replace @Autowired and @Qualifier with @Resource and the attribute “name” as in the following example:

The following table is a summary of the full post:

@Autowired @Resource
Spring annotation JSR-250
injection by type
or injection by name with @Qualifier
injection by name
mandatory but not with required = false mandatory

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.