Spring Bean Autowiring – @Autowired

In Spring framework, declaring bean dependencies in configuration files is a good practice to follow, so the Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your beans by inspecting the contents of the BeanFactory. This is called spring bean autowiring.

With latest String versions, we should use annotation based Spring configuration.

The autowiring functionality has four modes. These are ‘no‘, ‘byName‘, ‘byType‘ and ‘constructor‘.

Another autowire mode autodetect has been deprecated. Docs says that the “autodetect” option provided too much “magic” and a more explicit declaration is preferred.
  • The default autowire mode in XML configuration is no.
  • The default autowire mode in java configuration is byType.
Spring bean autowiring modes
Spring bean autowiring modes
Table of Contents

1. Autowiring modes
2. @Autowired annotation
3. @Qualifier for conflict resolution
4. Error safe autowiring
5. Excluding a bean from autowiring

1. Autowiring modes

As shown in the picture above, there are five auto wiring modes. Let’s discuss them one by one.

  1. no

    This option is default for spring framework and it means that autowiring is OFF. You have to explicitly set the dependencies using <property> tags in bean definitions.

  2. byName

    This option enables the dependency injection based on bean names. When autowiring a property in a bean, the property name is used for searching a matching bean definition in the configuration file. If such a bean is found, it is injected into the property. If no such bean is found, an error is raised.

    Read More : Autowire byName example

  3. byType

    This option enables the dependency injection based on bean types. When autowiring a property in bean, the property’s class type is used for searching a matching bean definition in the configuration file. If such a bean is found, it is injected into the property. If no such bean is found, an error is raised.

    Read More : Autowire byType example

  4. constructor

    Autowiring by constructor is similar to byType, but applies to constructor arguments. In autowire enabled bean, it will look for class type of constructor arguments, and then do a autowire bytype on all constructor arguments. Please note that if there isn’t exactly one bean of the constructor argument type in the container, a fatal error is raised.

    Read More : Autowire by constructor example

2. @Autowired annotation

Apart from the autowiring modes provided in the bean configuration file, autowiring can be specified in bean classes also using @Autowired annotation. To use @Autowired annotation in bean classes, you must first enable the annotation in the spring application using the below configuration.

2.1. Enable annotation config

<context:annotation-config />

Same can be achieved using AutowiredAnnotationBeanPostProcessor bean definition in configuration file.

<bean class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

2.2. Using @Autowired annotation

Now, when annotation configuration has been enabled, you are free to autowire bean dependencies using @Autowired, the way you like. This is done in three ways:

2.2.1. @Autowired on properties

When @Autowired is used on properties, it is equivalent to autowiring by ‘byType‘ in configuration file.

public class EmployeeBean
{
    @Autowired
    private DepartmentBean departmentBean;

    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
	//More code
}
2.2.2. @Autowired on property setters

When @Autowired is used on setters, it is also equivalent to autowiring by ‘byType‘ in configuration file.

public class EmployeeBean
{
    private DepartmentBean departmentBean;

    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }

	@Autowired
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
	//More code
}
2.2.3. @Autowired on constructors

When @Autowired is used on bean’s constructor, it is also equivalent to autowiring by ‘constructor‘ in configuration file.

package com.howtodoinjava.autowire.constructor;

public class EmployeeBean
{
    @Autowired
    public EmployeeBean(DepartmentBean departmentBean)
    {
        this.departmentBean = departmentBean;
    }

    private DepartmentBean departmentBean;

    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
	//More code
}

3. @Qualifier for conflict resolution

As we learned that if we are using autowiring in ‘byType‘ mode and dependencies are looked for property class types. If no such type is found, an error is thrown. But, what if there are two or more beans for the same class type.

In this case, spring will not be able to choose the correct bean to inject into the property, and you will need to help the container using qualifiers.

To resolve a specific bean using qualifier, we need to use @Qualifier annotation along with @Autowired annotation and pass the bean name in annotation parameter. Take a look below for example:

public class EmployeeBean
{
    @Autowired
	@Qualifier("finance")
    private DepartmentBean departmentBean;

    public DepartmentBean getDepartmentBean() {
        return departmentBean;
    }
    public void setDepartmentBean(DepartmentBean departmentBean) {
        this.departmentBean = departmentBean;
    }
	//More code
}

where duplicate beans are as below:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <context:annotation-config />

    <bean id="employee" class="com.howtodoinjava.autowire.constructor.EmployeeBean" autowire="constructor">
        <property name="fullName" value="Lokesh Gupta"/>
    </bean>

    <!--First bean of type DepartmentBean-->
    <bean id="humanResource" class="com.howtodoinjava.autowire.constructor.DepartmentBean" >
        <property name="name" value="Human Resource" />
    </bean>

	<!--Second bean of type DepartmentBean-->
	 <bean id="finance" class="com.howtodoinjava.autowire.constructor.DepartmentBean" >
        <property name="name" value="Finance" />
    </bean>
</beans>

4. Error safe autowiring with ‘required=false’ (Not Recommended)

Even if you have used the utmost care in autowiring bean dependencies, still you may find strange bean lookup failures. So, to solve this issue, you may want to make autowiring optional for some of the beans so that if those dependencies are not found, the application should not throw any exception.

This can be done in two ways:

  • If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.
    @Autowired (required=false)
    @Qualifier ("finance")
    private DepartmentBean departmentBean;
    
  • If you want to apply optional autowiring at global level i.e. for all properties in all beans; use below configuration setting.
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
        <property name="requiredParameterValue" value="false" />
    </bean>
    

5. Excluding a bean from autowiring

By default, autowiring scans, and matches all bean definitions in scope. If you want to exclude some bean definitions so that they can not be injected through autowiring mode, you can do this using ‘autowire-candidate‘ set to false.

  1. Using ‘autowire-candidate‘ as false totally exclude a bean from being an autowire candidate. It totally exclude that specific bean definition from being available to the autowiring infrastructure.
    <?xml version="1.0" encoding="UTF-8"?>
    <beans>
        <context:annotation-config />
    
        <bean id="employee" class="com.howtodoinjava.autowire.constructor.EmployeeBean" autowire="constructor">
            <property name="fullName" value="Lokesh Gupta"/>
        </bean>
        <!--Will be available for autowiring-->
        <bean id="humanResource" class="com.howtodoinjava.autowire.constructor.DepartmentBean" >
            <property name="name" value="Human Resource" />
        </bean>
    
        <!--Will not participate in autowiring-->
         <bean id="finance"      class="com.howtodoinjava.autowire.constructor.DepartmentBean" autowire-candidate="false">
            <property name="name" value="Finance" />
        </bean>
    </beans>
    
  2. Another option is to limit autowire candidates based on pattern-matching against bean names. The top-level <beans/> element accepts one or more patterns within its ‘default-autowire-candidates‘ attribute.

    For example, to limit autowire candidate status to any bean whose name ends with ‘Impl‘, provide a value of ‘*Impl‘. To provide multiple patterns, define them in a comma-separated list.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans default-autowire-candidates="*Impl,*Dao">
        <context:annotation-config />
    
        <bean id="employee" class="com.howtodoinjava.autowire.constructor.EmployeeBean" autowire="constructor">
            <property name="fullName" value="Lokesh Gupta"/>
        </bean>
        <!--Will be available for autowiring-->
        <bean id="humanResource" class="com.howtodoinjava.autowire.constructor.DepartmentBean" >
            <property name="name" value="Human Resource" />
        </bean>
    
        <!--Will not participate in autowiring-->
         <bean id="finance"      class="com.howtodoinjava.autowire.constructor.DepartmentBean" autowire-candidate="false">
            <property name="name" value="Finance" />
        </bean>
    </beans>
    

Note that an explicit value of ‘true‘ or ‘false‘ for a bean definition’s ‘autowire-candidate‘ attribute always takes precedence, and for such beans, the pattern matching rules will not apply.

That’s all about Spring bean autowiring. If you have any doubt, please drop a comment.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

25 thoughts on “Spring Bean Autowiring – @Autowired”

  1. @Autowired is used on properties, it is equivalent to autowiring by ‘byType‘ in configuration file.

    @Autowired is used on setters, it is also equivalent to autowiring by ‘byType‘ in configuration file.

    Are you sure about these two ?

    If yes then how you will apply auto detect strategy ?

    Reply
  2. very good explanations with examples which is really a help. Thanks a lot. Could you please add some spring data access tutorial as well, it will be a great help. Thanks in advance.

    Reply
  3. Injecting beans with xml file is obsolete. Please update the article by presenting Java config classes. Also some examples would be welcomed here.

    Reply
  4. XML formatting is not working on the page.

    this is how it is showing.

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
        <property name="requiredParameterValue" value="false" />
    </bean>
    Reply
  5. Nice Explanation..
    But i have one doubt, if one bean is of singleton type and another is of non- singleton(say:- prototype) and we are trying to @Autowired non singleton into singleton bean, So in that case this @Autowired will work or should we pass any parameter while autowiring? because both have different type.

    Reply
  6. Nice explained in the detailed and crispy manner. Mr. Gupta proud to find a person who accept blames and in response gives another place to refer.

    Reply
  7. Hi Lokesh,

    I am trying to Autowire a bean with @Autowired annotation finally messed up with following errors from 2 days, could you pls help me in understanding the issue

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': 
    Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
    Could not autowire field: private com.emusicstore.dao.ProductDAO com.emusicstore.app.HomeController.productDAO; 
    nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productDAOImpl':
     Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
    Could not autowire field: private org.hibernate.SessionFactory com.emusicstore.dao.impl.ProductDAOImpl.sessionFactory; 
    nested exception is org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: 
    Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: 
    Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
    PropertyAccessException 1: org.springframework.beans.MethodInvocationException: 
    Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: 
    Could not load JDBC driver class [com.mysql.jdbc.Drive]
    Reply
  8. Nice explanation. Just few questions :
    1. what if in case of When @Autowired is used on properties ::: property type is of interface type. i.e. ref variable is of interface but we need to inject child type of that interface.

    Reply
  9. “if no dependency is found, application should not throw any exception and autowiring should simpy be ignored.” Strongly disagree with this.
    You intended to autowire a bean so not finding it means your config is wrong. And you need to find this out the earliest point you can: context start up. Better not start a missconfigured, not working application. I say always use @Required annotation or required=true property in @Autowired.

    Reply
  10. Thanks Lokesh Gupta for sharing such valuable tutorials.It is very nicely explained tutorial.

    I get how to do autowiring but i did’t get why we need autowiring and what is autowiring .If you can exaplain it i wold be greatefull of you.

    Reply
    • If you want to inject spring’s beans dependencies from one bean to another, then you should configure them in someplace so that the spring container can read the suitable dependency for you and inject it in runtime. This was done by using applicationContext.xml file in previous spring versions. Now you can define these dependencies using annotations (@Autowired). Spring container read that annotation and search the matching dependency in all available container-managed beans and inject the appropriate bean if found one.

      Reply
  11. Rk, I am happy that you cared and shared your thoughts. What docs says, I agree with it. I am also saying “If there are no matching beans,
    nothing happens; the property is not set.”
    For reference regarding multiple, please read the table content in section “Table 3.2. Autowiring modes” in these spring 3 docs.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.