What is Autowired In Spring Boot - onlyxcodes

Thursday 27 April 2023

What is Autowired In Spring Boot

In this tutorial, I will show you about the @Autowired annotation in the Spring Boot.


@Autowired is an annotation in Spring Boot that is used for automatic dependency injection. It enables you to add dependencies to your classes without explicitly creating the objects. This can speed up processing and make your code simpler.


When you add the @Autowired annotation to a class field or constructor, Spring Boot will automatically look for and inject a compatible object into your class from its context. The type of the annotated field or constructor argument should be the same as the type of the object.


autowired in spring boot

Let's look at a Spring Boot @Autowired annotation example.


Create a New Spring Boot Project

Here, a new Spring Boot project is generated from the Spring Initializr website.


Step 1 – Bootstrap your Spring Boot applications using the http://start.spring.io/ tool, as demonstrated in the following diagram. 


1. Select Maven Project


2. Select Java language


3. Select 2.7.11 Spring Boot Version


Note: Although I chose spring boot version 2.7.11 above, the version may change if you visit the spring initializr website.


Let's fill up every field in the project metadata.


Group – com.onlyxcodes. It is a common package name.


Artifact – AutowiredExample. This is our project name.


Description – Autowired Annotation Example in Spring Boot


Package Name – com.onlyxcodes.app. We will bootstrap some other packages inside this package and execute our application. 


Packaging – Select Jar. It includes needed jar files.


Java – I choose Java 8, but if you utilize Java 11 or 17 on your PC, you may also choose from versions 11 and 17.


5. Click the ADD DEPENDENCIES button in the right sidebar. 


Search for and include the Spring Web dependency when launching a custom window.


6. To download the project zip file instantly, click the GENERATE button in the bottom section last. 


a new spring boot project is generated from the spring initializr website

I have assumed you have installed Spring Tool Suite in your system.


Step 2 – Open the Spring Too Suite Tool. Go to File and select Import as seen in the following diagram.


open the spring tool suite. go to file and select import

Step 3 – To view the Open custom window, select Projects from Folder or Archive.


to view the open custom window, select projects from folder or archive.

Step 4 – Click the Archive button in the right sidebar to open the custom window once more. 


click the archive button in the right sidebar to open the custom window once more

Step 5 – From the download folder's location, choose the zip file containing the AutowiredExample project.


from the download folder's location, choose the zip file containing the autowiredexample project

Step 6 – View the project's imported zip file. The AutowiredExample.zip_expanded checkbox is not required, so kindly deselect it. Select "Finish" from the menu.


view the project's imported zip file. the autowiredexample.zip_expanded checkbox is not required, so kindly deselect it

The full directory structure for the project, including the additional packages we will develop for it, is shown below. 


the full directory structure for the project, including the additional packages

pom.xml

Since we created a maven-based project, spring boot automatically configures all our dependencies.


spring-boot-starter-web:- This dependency is primarily used when creating Spring MVC-based web applications incorporating RESTful APIs. Tomcat is used as the standard embedded container.


<?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.7.11-SNAPSHOT</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.onlyxcodes</groupId>
	<artifactId>AutowiredExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>AutowiredExample</name>
	<description>Autowired Annotation Example In Spring Boot</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-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>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<releases>
				<enabled>false</enabled>
			</releases>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<releases>
				<enabled>false</enabled>
			</releases>
		</pluginRepository>
	</pluginRepositories>

</project>

Create Model Class

Inside the com.onlyxcodes.app.model package, I created the Country Model class.


Three fields id, name, and state are described in this class and come under the setter and getter methods.


Also, I provided these fields a toString() call. The String representation of the object is returned by the toString() function.


The Java compiler internally calls the toString() function if any object is printed.


Country.java


package com.onlyxcodes.app.model;

public class Country {
	
	private int id;
	private String name;
	private String state;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	@Override
	public String toString() {
		return "Country [id=" + id + ", name=" + name + ", state=" + state + "]";
	}
	
}

Create a Service Class

I created the CountryService class and placed it in the com.onlyxcodes.app.service package.


Using the ArrayList() constructor, I created an ArrayList in this class.


Then I created the country class's C name object.


Then I set the values for the country class parameters using the C object. Id, name, and state are the parameters. 


Next, I used the add() method to add each element to an ArrayList.


The getCountryList() name function is then created with a List type and sent via the return statement.


CountryService.java


package com.onlyxcodes.app.service;

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

import org.springframework.stereotype.Service;

import com.onlyxcodes.app.model.Country;

@Service
public class CountryService 
{	
	private static List list = new ArrayList<>();
	
	static
	{
		Country c = new Country();
		c.setId(1);
		c.setName("Australia");
		c.setState("New South Wales");
		list.add(c);
		
		c = new Country();
		c.setId(2);
		c.setName("United States");
		c.setState("California");
		list.add(c);
		
		c = new Country();
		c.setId(3);
		c.setName("Canada");
		c.setState("Ontario");
		list.add(c);
	}
	
	public List getCountryList() 
	{
		return list;
	}
}

Create Controller Class

I created the controller class called CountryController and placed it in the com.onlyxcodes.app.controller package.


This class serves as our requests' Spring MVC controller. 


See Here,


I have implemented the @Autowired annotation in this class to inject objects into the CountryService class. The Country Service class object is automatically found by Spring Boot and injected into this class.


This class is marked as a @RestController, indicating that Spring MVC can use it to process web requests. 


The getAllList() method translates the @GetMapping method to "/" countries. 


The function returns the output when the URL http://localhost:8080/countries is called from a browser. 


That is so that web requests return data rather than a view as a result of the combination of @Controller and @ResponseBody in @RestController.


CountryController.java


package com.onlyxcodes.app.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 com.onlyxcodes.app.service.CountryService;

@RestController
public class CountryController 
{
	@Autowired
	CountryService countryService;
	
	@GetMapping("/countries")
	public List getAllList()
	{
		return countryService.getCountryList();
	}
}

Spring Boot Main Class

This class serves as the main class for Spring Boot applications and contains the public static void main() method, which runs the Spring Boot application. 


AutowiredExampleApplication.java


package com.onlyxcodes.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class AutowiredExampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(AutowiredExampleApplication.class, args);
		
	}

}

Output:


Execute the spring boot application, open your web browser, and type this URL http://localhost:8080/countries and see the output.


[{"id":1,"name":"Australia","state":"New South Wales"},{"id":2,"name":"United States","state":"California"},{"id":3,"name":"Canada","state":"Ontario"}]

@Autowired Annotation Different Modes Examples

I'll explore several simple instances of auto-wiring using the @Autowired annotation in different scenarios, including:


1) Property Based Autowiring


2) Setter Based @Autowired


3) Constructor Based @Autowired


1) Property Based Autowiring

Property-based auto wiring is one method of auto wiring in Spring.


When using property-based auto wiring, Spring looks at a bean's properties and makes an effort to match them with other beans in the application context. Spring injects the dependency into the bean if a match is discovered.


When the annotation is used directly on properties, as in the example below, Spring searches for and injects Company when the Headquarter object is created. 


It does it by doing away with the need for getters and setters.


Company Bean Class


First, the setter and getter methods are used to construct a bean class called "Company." 


This class has the annotation @Component.


Our custom beans can be instantly found by Spring thanks to the annotation @Component. Or, to put it another way, without writing any explicit code. 


When classes with the annotation @Component are found in our application, Spring will instantiate them and inject any specified dependencies into them. 


Company.java


package com.onlyxcodes.app.model;

import org.springframework.stereotype.Component;

@Component
public class Company {

	private String companyName;

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

}

Headquarter Bean Class


The setter and getter methods are then used to build the Headquarter bean class, the second bean class.


Additionally, this class carries the annotation @Component.


Look how we've injected the Company class object using the @Autowired annotation.


The name function showCompanyDetails() is developed within this class.


We set the company name, such as Apple, using the company class object and also retrieve it within the showCompanyDetails() function.


Headquarter.java


package com.onlyxcodes.app.model;

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


@Component
public class Headquarter {
	
	@Autowired
	private Company company;
	
	private String headquarterName;
	
	
	public String getHeadquarterName() {
		return headquarterName;
	}

	public void setHeadquarterName(String headquarterName) {
		this.headquarterName = headquarterName;
	}

	public void showCompanyDetails()
	{
		company.setCompanyName("Apple");
		System.out.println("Company Name : " +company.getCompanyName());
		System.out.println("Headquarter Name : " +headquarterName);
	}

}

Spring Boot Main Class


This is the spring boot application's main class, which runs the spring boot application.


In addition to the application context client methods in the ApplicationContext interface, the ConfigurableApplicationContext offers tools for configuring an application context.


The getBean() method of the ApplicationContext interface allows one to retrieve a bean from a spring container.


The Headquarter bean class is retrieved using the getBean() method.


We set the headquarters name and call the showCompanyDetails() function that we previously defined in the Headquarter class using the hq object of the Headquarter class.


The base and child packages' components, services, and other configuration files are all scanned by the @SpringBootApplication, which combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. This will register them in the Spring Context and use @Autowired to inject the beans at runtime.


Our application is launched by the main() method using Spring Boot's SpringApplication.run() method.


AutowiredExampleApplication.java


package com.onlyxcodes.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.onlyxcodes.app.model.Headquarter;

@SpringBootApplication
public class AutowiredExampleApplication {

	public static void main(String[] args) {
	
		ConfigurableApplicationContext context = SpringApplication.run(AutowiredExampleApplication.class, args);
		
		Headquarter hq = context.getBean(Headquarter.class);
		hq.setHeadquarterName("California");
		hq.showCompanyDetails();
	}

}

Output:


Company Name : Apple
Headquarter Name : California

2) Setter Based @Autowired

Use setter methods to inject dependencies into a Spring bean using setter-based auto wiring. This is accomplished by adding the @Autowired annotation to the setter methods.


When the annotation is used on the setter method in the example below, the setter method is called with the Company instance when the Headquarter is created.


We developed a Company bean class and used the setter and getter methods. 


This class has the annotation @Component. 


In the last section of the property-based annotation, we explained what the @Component annotation is.


Company.java


package com.onlyxcodes.app.model;

import org.springframework.stereotype.Component;

@Component
public class Company {

	private String companyName;

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

}

We develop the Headquarter bean class and use the setter and getter methods.


The setter and getter methods are likewise used for the company class.


Additionally, this class carries the annotation @Component. In this case, the Company class is dependent on the Headquarter class. 


When the Headquarter bean is created, Spring will automatically inject an instance of Company into the company field if the setCompany() function has the annotation @Autowired.


@Autowired
public void setCompany(Company company) {
	this.company = company;
}

The name function showCompanyDetails() is developed within this class.


We set the company name, such as IBM, using the company class object and also retrieve it within the showCompanyDetails() function.


Headquarter.java


package com.onlyxcodes.app.model;

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


@Component
public class Headquarter {
	
	private Company company;
	
	private String headquarterName;
	
	
	public String getHeadquarterName() {
		return headquarterName;
	}

	public void setHeadquarterName(String headquarterName) {
		this.headquarterName = headquarterName;
	}
	
	public Company getCompany() {
		return company;
	}

	@Autowired
	public void setCompany(Company company) {
		this.company = company;
	}

	public void showCompanyDetails()
	{
		company.setCompanyName("IBM");
		System.out.println("Company Name : " +company.getCompanyName());
		System.out.println("Headquarter Name : " +headquarterName);
	}

}

Spring Boot Main Class


Friends, Since we already covered the ConfigurableApplicationContext and ApplicationContext, I'll skip over their explanations.


This is the spring boot application's main class, which runs the spring boot application.


The getBean() method of the ApplicationContext interface allows one to retrieve a bean from a spring container.


The Headquarter bean class is retrieved using the getBean() method.


We set the headquarter name and execute the showCompanyDetails() function that we previously defined in the Headquarter class using the hq object of the Headquarter class.


Our application runs by the main() method using Spring Boot's SpringApplication.run() method.


AutowiredExampleApplication.java


package com.onlyxcodes.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.onlyxcodes.app.model.Headquarter;

@SpringBootApplication
public class AutowiredExampleApplication {

	public static void main(String[] args) {
		
		ConfigurableApplicationContext context = SpringApplication.run(AutowiredExampleApplication.class, args);
		
		Headquarter hq = context.getBean(Headquarter.class);
		hq.setHeadquarterName("New York");
		hq.showCompanyDetails();
	}

}

Output:


Company Name : IBM
Headquarter Name : New York

3) Constructor Based @Autowired

It's essential to note that injecting dependencies into Spring is not limited to setter-based auto wiring. 


Another popular technique is constructor-based auto wiring, which includes injecting dependencies via a constructor rather than through setter methods.


The constructor with the appropriate parameter types is used to instantiate the class and inject the dependencies once the spring container has examined the class's dependencies.


Use the @Autowired annotation on the class's constructor to allow constructor-based auto-wiring.


In the example below, the annotation is applied to a constructor, and when the Headquarter object is constructed, a Company instance is injected as an argument to the constructor.


We developed a Company bean class and used the setter and getter methods. 


This class has the annotation @Component. 


Company.java


package com.onlyxcodes.app.model;

import org.springframework.stereotype.Component;

@Component
public class Company {

	private String companyName;

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

}

We create the second bean class called Headquarter and apply the setter and getter method.


We also apply the setter and getter method to the company class.


This class also is marked as @Component annotation.


In this example, the Headquarter constructor has a single parameter of type Company, which is annotated with @Autowired. 


When the Spring container creates an instance of Headquarter, it will look for a bean of type Company and inject it into the constructor.


Note that if there are multiple constructors in a class, then you need to annotate only one constructor with @Autowired. Spring container will use that constructor for auto wiring.


@Autowired
public Headquarter(Company company) {
	System.out.println("*** Constructor based @Autowired annotation ***");
	this.company = company;
}
	

The name function showCompanyDetails() is developed within this class.


Using the company class object, we set the company name as "Oracle" and retrieve it in the showCompanyDetails() function.


Headquarter.java


package com.onlyxcodes.app.model;

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


@Component
public class Headquarter {
	
	private Company company;
	
	private String headquarterName;
	
	@Autowired
	public Headquarter(Company company) {
		System.out.println("*** Constructor based @Autowired annotation ***");
		this.company = company;
	}
	
	public String getHeadquarterName() {
		return headquarterName;
	}

	public void setHeadquarterName(String headquarterName) {
		this.headquarterName = headquarterName;
	}
	
	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public void showCompanyDetails()
	{
		company.setCompanyName("Oracle");
		System.out.println("Company Name : " +company.getCompanyName());
		System.out.println("Headquarter Name : " +headquarterName);
	}

}

Spring Boot Main Class


This is the spring boot application's main class, which runs the spring boot app.


The getBean() method of the ApplicationContext interface allows one to retrieve a bean from a spring container.


The Headquarter bean class is retrieved using the getBean() function.


We set the headquarter name and execute the showCompanyDetails() function that we previously defined in the Headquarter class using the hq object of the Headquarter class.


Our application is executed by the main() method using Spring Boot's SpringApplication.run() method.


AutowiredExampleApplication.java


package com.onlyxcodes.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.onlyxcodes.app.model.Headquarter;

@SpringBootApplication
public class AutowiredExampleApplication {

	public static void main(String[] args) {
		
		ConfigurableApplicationContext context = SpringApplication.run(AutowiredExampleApplication.class, args);
		
		Headquarter hq = context.getBean(Headquarter.class);
		hq.setHeadquarterName("Austin, Texas");
		hq.showCompanyDetails();
	}

}

Output:


*** Constructor based @Autowired annotation ***
Company Name : Oracle
Headquarter Name : Austin, Texas

No comments:

Post a Comment

Post Bottom Ad