• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

@Autowired Annotation in Spring

April 18, 2013 //  by Manisha Patil//  Leave a Comment

This tutorial explains how to use @Autowired annotation for injecting the spring beans with simple example. This tutorial helps reader to understand various ways to use @Autowired in your application. Enjoy happy reading!!!

Autowired annotation in spring framework

In my previous post I mentioned about the use of @Required annotation for container configuration. In this post I shall cover the @Autowired annotation. Spring bean dependencies are defined in the XML files (Also Read : Introduction to Spring Boot), the same can be automatically detected by the Spring container by using the @Autowired annotation. This would eliminate using the XML configurations. Introduced in Spring 2.5, the @Autowired annotation can be applied to

  1. On setter methods
  2. On Properties
  3. On Constructors
  4. @Autowired with arguments

Let us see an example for each of the above. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

  1. Create a project: Create a project with a name SpringAnnotationExamples and create a package com.javabeat.autowireexample under the src directory in the created project.
  2. Add Libraries: Add required Spring libraries using Add External JARs option as explained in the article Customizing callback methods.
  3. Create source files: Create Java classes Product,Type and MainApp under the com.javabeat.autowireexample package.
  4. Create configuration file: Create XML based configuration file BeansAutowireAnnotation.xml under src directory.

@Autowired Annotation Example

1. @Autowired on setter methods

When spring containers finds @autowired annotation with setter methods,it autowires bean byType .

byType – Allows a property to be autowired if exactly one bean of the property type exists in the container.

The class Product.java, is simple POJO class having name,price and an object of Type class.

Contents of Product.java are:

 package com.javabeat.autowireexample;

 import org.springframework.beans.factory.annotation.Autowired;

 public class Product {
 	private Integer price;
 	private String name;
 	private Type type;

 	public Integer getPrice() {
 		return price;
 	}

 	public void setPrice(Integer price) {
 		this.price = price;
 	}

 	public Type getType() {
 		return type;
 	}

 	@Autowired
 	public void setType(Type type) {
 		this.type = type;
 	}

 	public String getName() {
 		return name;
 	}

 	public void setName(String name) {
 		this.name = name;
 	}
 }
 

The Type.java class is also a POJO class having a string object called “type”.

Contents of Type.java are:

 package com.javabeat.autowireexample;

 public class Type {

 	private String type;

 	public String getType() {
 		return type;
 	}

 	public void setType(String type) {
 		this.type = type;
 	}
 }
 

Contents of MainApp are:

 package com.javabeat.autowireexample;

 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class MainApp {
 	public static void main(String[] args) {
 		ApplicationContext context = new ClassPathXmlApplicationContext(
 				"BeansAutowireAnnotation.xml");

 		Product product = (Product) context.getBean("product");

 		System.out.println("Product Name : " + product.getName());
 		System.out.println("Price : " + product.getPrice());

 		Type productType = product.getType();

 		System.out.println(product.getName() + " is of type:"
 				+ productType.getType());
 	}
 }

Contents of BeansAutowireAnnotation.xml are:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<context:annotation-config />

	<!-- Definition for Product bean -->
	<bean id="product" class="com.javabeat.autowireexample.Product">
		<property name="name" value="ProductA" />
		<property name="price" value="400" />
	</bean>
	<bean id="type" class="com.javabeat.autowireexample.Type">
		<property name="type" value="Export" />

	</bean>

</beans>

We see that there is no relation between the two beans “product” and “type”. The @autowired annotation which we have used on the setter method in Product.java class, will automatically wire above beans on the basis of type.

Execute the code

The final step is run the application. Once all the above code is ready execute and the below output appears on the console:

Product Name : ProductA
Price : 400
ProductA is of type:Export

2. @Autowired On Properties

We can use @Autowired annotation for properties or fields. This helps us to get away with the setter methods. This is demostrated in the example below. I shall use the above example, only change made would be in the Product.java file, contents of this file are as below:

package com.javabeat.autowireexample;

import org.springframework.beans.factory.annotation.Autowired;

public class Product {
	private Integer price;
	private String name;
	@Autowired
	private Type type;

	public Integer getPrice() {
		return price;
	}

	public void setPrice(Integer price) {
		this.price = price;
	}

	public Type getType() {
		return type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Here we see that the @Autowired is used for the property “type” and no setter method is provided. When we pass values of autowired properties using <property>, Spring will automatically assign those properties with the passed values or references.
If you execute the code now, the output would as below:

Product Name : ProductA
Price : 400
ProductA is of type:Export

3. @Autowired On Constructors

We can use @Autowired annotation for Constructors. The following example demonstrates this: I shall use the above example, only change made would be in the Product.java file. The contents of this file are :

package com.javabeat.autowireexample;

import org.springframework.beans.factory.annotation.Autowired;

public class Product {
	private Integer price;
	private String name;

	@Autowired
	public Product(Type type) {
		super();
		this.type = type;
                System.out.println("Inside Product constructor.");
	}

	private Type type;

	public Integer getPrice() {
		return price;
	}

	public void setPrice(Integer price) {
		this.price = price;
	}

	public Type getType() {
		return type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Execute the code and the output would be as below:

Inside Product constructor.
Product Name : ProductA
Price : 400
ProductA is of type:Export

4. @Autowired with arguments

The default behavior of of autowiring is to treat annotated methods, constructors, and fields as required dependencies. We can change this by turning off the default behavior by using (required=false) option with @Autowired as demonstrated below:

I shall use the same example, only changes would be made to Product.java and BeansAutowireAnnotation.xml files.

Contents of Product.java file are:

package com.javabeat.autowireexample;

import org.springframework.beans.factory.annotation.Autowired;

public class Product {
	private Integer price;
	private String name;

	@Autowired(required=false)
	private Type type;

	public Integer getPrice() {
		return price;
	}

	public void setPrice(Integer price) {
		this.price = price;
	}

	public Type getType() {
		return type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

The contents of BeansAutowireAnnotation.xml file are:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<context:annotation-config />

	<!-- Definition for Product bean -->
	<bean id="product" class="com.javabeat.autowireexample.Product">
		<property name="name" value="ProductA" />
		<property name="price" value="400" />
	</bean>
	<bean id="type" class="com.javabeat.autowireexample.Type">
		<!-- <property name="type" value="Export" /> -->
	</bean>

</beans>

Here I’ve commented out the property field “type”. Now execute the code and the output would be:

Product Name : ProductA
Price : 400
ProductA is of type:null

Apart from the above, the @Autowired annotation can also be used for:

  • A field or method that expects an array of that type
  • For typed collections
  • For typed Maps (as long as the expected key type is String)
  • For interfaces that are well-known resolvable dependencies: BeanFactory, ApplicationContext, Environment, ResourceLoader, ApplicationEventPublisher, and MessageSource.

Summary

In this post we saw how to configure the Spring container using the @Autowired annotation. This annotation can be used for on setter methods, on fields, on constructors, with arguments. Examples for the same has been demonstrated. In the next article I shall discuss about how to fine tune annotation-based autowiring with qualifiers.

If you are interested in receiving the future articles, please subscribe here

Thank you for reading my blog!! Happy Learning!!

Category: Spring FrameworkTag: Spring Framework

About Manisha Patil

Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Previous Post: «New Features in Spring Boot 1.4 @Required Annotation in Spring
Next Post: @Qualifier Annotation in Spring New Features in Spring Boot 1.4»

Reader Interactions

Leave a Reply Cancel 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.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact