dir.by  
  Search  
Programming, development, testing
Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
  Looked at 1426 times       Comments 2  
 Last Comment: (10 October 2025 9:36) Добрый день! Спасибо read...       Write a comment...
 What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java 
last updated: 7 April 2025
DI (Dependency Injection) is used when classes depend on each other.
For example: A class in a constructor needs another class.
  Java  
public class Book
{
     ...

     public Book(Author author)
     {
          _author = author;
     }
}


The Spring library automatically creates nested objects by itself.
Spring will create a Author object, but you need to specify the dependency injection type .

Dependency injection type - this is the place where one class will be injected into another:
1) In the constructor
I'll use in my example below
2) In the setter
3) In the class field
My example:
There is a class Book
There is a class Author
When creating Book, you need Author

Why should I use Spring, Dependency Injection if I can create my objects in 2 lines:
  Java  
Author author = new Author();
Book book = new Book(author);


Answer: Because a good style is to specify through the dependency attribute, and Spring will create nested objects by itself.
And the biggest advantage is that when you create nested objects, they become loosely coupled (Spring creates automatically) and this makes it less code and easier to write tests.
What is Spring Bean and how do I specify dependencies in different bean?
Spring Bean is a regular object that is not created by me, but the object is created by Spring Container.
  Java  
ApplicationContext context = new ClassPathXmlApplicationContext("MyConfig.xml"); // Create Spring Container from the configuration file
Book book = (Book) context.getBean("myBookBean");
Spring by name myBookBean creates Book.
And since Author is needed internally, using dependency injection creates Author
Dependent objects Spring Container are created by itself

Spring Container knows how to create Book because I use the @Component attribute:
At the beginning of the class, I will use @Component(" come up with any name for bean").
To inject the dependency, I will use the @Autowired annotation in the constructor
  Java  
@Component("myBookBean")
public class Book // Class Book is bean with the name myBookBean
{
     ...

     @Autowired
     public Book(Author author)
     {
          _author = author;
     }
}
 
At the beginning of the class, I will use @Component(" come up with any name for bean").
  Java  
@Component("myAuthorBean")
public class Author // Class Author is bean with the name myAuthorBean
{
     ...

     public Author()
     {
          _authorName = "Mark Twain";
     }
}
 
In the configuration file for context:component I wrote base-package (where our classes are located):
  Xml  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"...>

     <context:component-scan base-package="com.example.springproj1" />

</beans>
 
Which configuration is best for IoC Spring Container (from this configuration, Spring will know how to create bean):
configuration in the XML file ... (used in older programs)
• configuration via @Component, @Autowired attributes (used in modern programs and I use in my example below)
• configuration via Java code using @Configuration, @ComponentScan, @Bean (sometimes used)
 
Configuration for IoC Spring Container is an explanation for IoC Spring Container how to create bean objects.
Someone who controls and can manage all of your classes is called ApplicationContext (IoC Spring Container)
Creating a simple Spring project with Dependency Injection in the constructor | Editor IntelliJ Idea and language Java
Download an example:
SpringProj_DI.zip ...
size: 20 kb
Note! You must have Java JDK installed. If you don't have it, then need to download and install Java JDK ...

Note! You must have IntelliJ IDEA Ultimate installed. If you don't have it, then need to download and install IntelliJ IDEA ...
Step 1. Create a new project with the type Spring Boot
 
Select Spring Boots:
 
Since we have a simple project, do not check the boxes:
 
The project was created:
Step 2. Create a new Book.java file
Right-click on my package folder and create a new java file
 
Let's write the name Book
And choose the type Class
Press Enter
The file was created.
 
Inside the Book.java file, add the code:
package com.example.springproj1;

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

@Component("myBookBean")
public class Book {

     protected String _name;
     protected Author _author;

     @Autowired
     public Book(Author author)
     {
          _name = "Tom Sawyer";
          _author = author;
     }

     public void ShowBook()
     {
          System.out.println(_name);
          _author.ShowAuthor();
     }
}
Step 3. Create a new Author.java file
package com.example.springproj1;

import org.springframework.stereotype.Component;

@Component("myAuthorBean")
public class Author {
     protected String _authorName;

     public Author()
     {
          _authorName = "Mark Twain";
     }

     public void ShowAuthor()
     {
          System.out.println(_authorName);
     }
}
Step 4. Create a new configuration MyConfig.xml file
Right-click on the folder resources and create a new Spring Config file
 
Let's write the name MyConfig
Press Enter
The file was created.
 
Inside the MyConfig.xml file, add the code:
<?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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

     <context:component-scan base-package="com.example.springproj1" />

</beans>
Step 5. In the application java file, add the code
package com.example.springproj1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//@SpringBootApplication
public class SpringProj1Application {

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

          ApplicationContext context = new ClassPathXmlApplicationContext("MyConfig.xml");
          Book book = (Book) context.getBean("myBookBean");
          book.ShowBook();

     }

}
 
Note!
// Option 1
Book book = (Book) context.getBean("myBookBean");

// Or you can do it like this

// Option 2
Book book = context.getBean("myBookBean", class.Book);
Note!
In order for Spring to create bean, I had to comment //@SpringBootApplication in the SpringProj1Application.java file
Step 6. Launching the project
To start the project, you need to open the application java file and click on the green triangle:
 
After launching the program, we will see the result on the screen:
Tom Sawyer
Mark Twain
 
← Previous topic
What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
 
Next topic →
Creating a new Spring web application (Controller responds to request) | Java, Spring Web, Spring Boot, Maven
 
Your feedback ... 1 Comments
guest
10 October 2025 8:47
Доброго времени суток! Уважаемый Автор данного ресурса, выражаю вам благодарность за подробнейшие разъяснения и скрины! Возможно вы этого не прочтете, но знайте что вы принесли большой вклад в понимании этой темы, для начинающего разработчика.
admin (10 October 2025 9:36) Добрый день! Спасибо answer
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
Download and install
Installation JDK (download and install the Java library for Windows)
Download and install IntelliJ IDEA to explore Java, Spring, Jakarta EE | Functionality and differences: Community | Ultimate
Learn the language Java (class, interface, properties, etc.)
Create a simple console app in IntelliJ IDEA to learn Java
What is interface in Java ?
Directly in the code (at runtime) we make an implementation for the interface | Java
Java web application (servlet, jsp page, basic functionality and no frameworks)
Creating a new simple web application (jsp web page) | Java, Maven
Create a web servlet (the servlet is located on the web server, returns the result on request) | Java
Installation Tomcat web server (download and install for Windows)
Check, test Tomcat web server (create a new my.hml file)
What is Maven
What is a dynamic web page jsp (Java Server Page) ?
How to install Smart Tomcat plugin in Intellij Idea
Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
What is Spring? Why use Spring in Java?
What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
Creating a new Spring web application (Controller responds to request) | Java, Spring Web, Spring Boot, Maven
Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
Create Azure Web App with the type Java (free). That is, create an empty web server
Put the Java Spring web application in Azure
Connect to the application Azure Web App (Java) via FTP | use File Explorer
Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java, Spring Boot
How to install Spring WebSocket plugin in Intellij Idea
Jakarta EE / Java EE in Java (Web Applications, Web Services)
What is Jakarta EE (Java EE)? | In which editor (program) is it convenient to write Jakarta EE (Java EE) code?
Creating a simple web project in IntelliJ Idea Ultimate | Jakarta EE (Java EE)
Struts in Java (extends API Java Servlet using MVC)
What is Struts | Java
Interviews on Java

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика