dir.by  
  Search  
Programming, development, testing
Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
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
  Looked at 2904 times       Comments 5  
 Last Comment: (4 February 2025 10:38) Спасибо, вы правы есть ошибка в [java_code]Book book =... read...       Write a comment...
 What is Spring Bean, 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 
last updated: 7 April 2025
I create a regular object like this:
  Java  
Book book = new Book();
What is Spring Bean?
Spring Bean This is a regular object that is not created by me, but the object is created by Spring Container.
  Java  
// Spring Container creates bean.
ApplicationContext context = new ClassPathXmlApplicationContext("MyConfig.xml"); // Create Spring Container from the configuration file
Book book = (Book) context.getBean("myBook1"); // Spring Container creates a book object by id
  Spring Container knows how to create my object(Bean) because everything is described in the configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans>

     <bean id="myBook1" class="com.example.springproj1.Book">
     </bean>

</beans>
Note! Why use Spring to create an object when you can create my object in one line:
Book book = new Book();
Answer: Because it's a good style to describe all objects in a single configuration file xml.
What is Spring Container?
Spring Container is responsible for creating Bean (my object).

Spring Container performs 2 functions: IoC and DI
IoC - inversion of control (you do not create and manage objects, the library Spring creates and manages objects itself)
 
Interface org.springframework.context.ApplicationContext represents IoC Spring Container and is responsible for creating, configuring Bean because it inherits from interface BeanFactory.
ApplicationContext (IoC Spring Container) knows how to create objects, but needs to be configured.
 
You can make a configuration for IoC Spring Container using:
  1) XML file (I use it in my example below)
    The ClassPathXmlApplicationContext class is an implementation of the ApplicationContext interface.
    The ClassPathXmlApplicationContext class takes the configuration from the XML file.
 
  2) Annotations in Java: @Service, @Component, @Scope
 
  3) Java code: @Configuration, @ComponentScan, @Bean
    @Configuration indicate configuration class.
    @Bean indicate method that create bean.

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)
DI - Dependency Injection (used to create complex objects)
 
Note! In my example below, I don't use Dependency Injection. Because I have only one class in my example.
And for Dependency Injection you need two classes that depend on each other


DI Spring is when a class needs another class...
Create a simple Spring project and configure Spring Bean in an XML file | Editor IntelliJ Idea and language Java
Download an example:
SpringProj1.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;

public class Book {
     public String name;

     public Book()
     {
          name = "Tom Sawyer";
     }
}
Step 3. 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 bean a description:
Spring reads the bean description from the xml file and knows how to create the bean object in the future.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="myBook1" class="com.example.springproj1.Book">
     </bean>


</beans>
Step 4. Add the code to the SpringProj1Application.java file
// Spring Container creates bean.
ApplicationContext context = new ClassPathXmlApplicationContext("MyConfig.xml"); // Create Spring Container from the configuration file
Book book = (Book) context.getBean("myBook1"); // Spring Container creates a book object by id

// Showing the result on the screen
System.out.println("See what book created: " + book.name); // Displaying the name of the book
 
Note!
// Option 1
Book book = (Book) context.getBean("myBook1");

// Or you can do it like this

// Option 2
Book book = context.getBean("myBook1", Book.class);
Step 5. 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:
See what book created: Tom Sawyer
 
← Previous topic
What is Spring? Why use Spring in Java?
 
Next topic →
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
 
Your feedback ... 2 Comments
guest
17 January 2025 12:13
СПАСИБО!!!!!

Я 3 раза пытался понять эту базу с разных источников, только Ваша статья помогла.
admin (17 January 2025 17:21) Спасибо :) answer
Donkey
3 February 2025 21:30
спасибо большое за статью, продолжаю читать и практиваться по ней.

Donkey (3 February 2025 21:59) // Вариант 2
Book book = context.getBean("myBook1", class.Book);
Не ялвяется ли это ошибкой?
answer
admin (4 February 2025 10:38) Спасибо, вы правы есть ошибка в
  Java  
Book book = context.getBean("myBook1", class.Book Book.class);

исправил
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  
Яндекс.Метрика