Spring boot @Autowire annotation with example





Hey guys in this post, we will discuss @Autowire annotation in spring with an example

Overview


@Autowire annotation can be applied to a constructor, field, or setter method. It helps to autowire the bean without creating an object using the new keyword.

First, and most important – all Spring beans are managed – they “live” inside a container, called “application context”.

Second, each application has an entry point to that context. Also, there is a place where the application context is bootstrapped and all beans – autowired. In web applications, this can be a startup listener.

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

What is “living” in the application context? This means that the context instantiate the objects, not you. I.e. – you never make new UserServiceImpl() – the container finds each injection point and sets an instance there.

In your controllers, you just have the following:

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

Watch the video


Example on @Autowire annotation


Let’s look at an example for @Autowire annotation by creating a spring boot project.

Create spring boot project


There are different ways to create a spring boot project, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>autowireannotation</artifactId>
	<version>v1</version>
	<name>autowireannotation</name>
	<description>Spring boot autowire annotation</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




spring-boot-devtools dependency for automatic reloads or live reload of applications.

Create an entity


Create Customer.java inside the in.bushansirgur.springboot.entity and add the following content

package in.bushansirgur.springboot.entity;

public class Customer {
	
	private Long id;
	
	private String name;
	
	private Long age;
	
	private String location;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public Long getAge() {
		return age;
	}

	public void setAge(Long age) {
		this.age = age;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + ", age=" + age + ", location=" + location + "]";
	}
}

Create a service


Create CustomerService.java inside the in.bushansirgur.springboot.service and add the following content

package in.bushansirgur.springboot.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import in.bushansirgur.springboot.entity.Customer;

@Service
public class CustomerService {
	private static List list = new ArrayList<>();
	static {
		Customer c = new Customer();
		c.setId(1L);
		c.setName("Customer 1");
		c.setAge(28L);
		c.setLocation("India");
		list.add(c);
		
		c = new Customer();
		c.setId(2L);
		c.setName("Customer 2");
		c.setAge(30L);
		c.setLocation("India");
		list.add(c);
		
		c = new Customer();
		c.setId(3L);
		c.setName("Customer 3");
		c.setAge(31L);
		c.setLocation("India");
		list.add(c);
	}
	
	public List getCustomerList() {
		return list;
	}
}

Create a controller


Create CustomerController.java inside the in.bushansirgur.springboot.controller and add the following content

package in.bushansirgur.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springboot.entity.Customer;
import in.bushansirgur.springboot.service.CustomerService;

@RestController
public class CustomerController {
	
	@Autowired
	CustomerService cService;
	
	@GetMapping("/customers")
	public List getList() {
		return cService.getCustomerList();
	}
}

Run the application


You can run the application by executing the below command

mvn spring-boot:run

Open the browser and type the following URLs and see the output http://localhost:8080/customers

[
{
"id": 1,
"name": "Customer 1",
"age": 28,
"location": "India"
},
{
"id": 2,
"name": "Customer 2",
"age": 30,
"location": "India"
},
{
"id": 3,
"name": "Customer 3",
"age": 31,
"location": "India"
}
]




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply