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 !!

Leave a Reply

25 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial