Common ways to store and read objects in Spring

The previous article briefly introduced the process of creating and using Spring. The method of storing objects and reading objects used in this article is very cumbersome, and the following will introduce a simpler method for you.

Store Bean objects

1. Configure the scan root path of the bean

<?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:content="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">
    <content:component-scan base-package=""></content:component-scan>
</beans>

insert image description here
Before storing objects, configure the scan package path for storing objects. Under the current path, the annotations will be scanned and stored in Spring.

2. Use annotations

1. Class annotation

Five categories of annotations
  • @Controller
    control layer, check the legality of parameters.
  • @Service
    service layer, to call several methods or interfaces, business assembly
  • @Repository
    data persistence layer, business implementation
  • @Component
    component (tool layer)
  • @Configuration
    configuration layer, make some settings for the current project

Adding one of the above five class annotations before the current class can realize the function of registering the object of this class in the Spring container.

@Controller
public class UserController {
    public void beauty(){
        System.out.println("你今天真漂亮!!!");
    }
}

When acquiring an object, the default acquired name is the first letter of the current class in lowercase.
In a special case: when the first letter and the second letter are both uppercase, the acquired name is the class name.
insert image description here

2. Method annotation

  • @Bean
    Note: It needs to be used in conjunction with the five major types of annotations, and a single Bean annotation is not enough.

Store the object returned by the current method in Spring.

@Component
public class Users {
    @Bean //把当前方法返回的对象存入String中
    public User getUser(){
        User user=new User();
        user.setId(1);
        user.setName("陈宇");
        user.setSex("男");
        return user;
    }
}

Store the user object in Spring, and the default name obtained by getBean is the method name.

ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
User user=context.getBean("getUser", User.class); 
System.out.println(user.toString());

result:
insert image description here

rename beans
  • @Bean(“”)
  • @Bean(name=“”)
  • @Bean(value="") (multiple names are supported)
    insert image description here
    insert image description here

At this time, the name of the object obtained by getBean needs to be set to the name in the annotation.

Note: After renaming, the object can no longer be obtained through the original method name.

When Spring stores Bean objects through the @Bean annotation, a Bean object can have multiple names. But what if different objects have the same name.
No error will be reported. But only one will be stored inside the container.
Which one to store?
If it is a different object of the same type, it is inferred based on the execution order of the code. The execution order of the code is from top to bottom.
If it is a different object of different types, it is selected according to the weight. The greater the weight, the earlier it is executed.

insert image description here
insert image description here

Read the Bean object

object injection

Take the object out and put it in a certain class.

1. Property injection

  • There is only one object of the same type, directly inject this object into the current property

Implemented through the @Autowired annotation.

Create a User object. Store the User object in Spring.

insert image description here

Inject the User class into UserService:

insert image description here

Test the code:
get the UserService object, if the getUser method can be executed successfully, the User object will be returned successfully. It means that the User class is successfully injected into UserService.
insert image description here

  • There are multiple objects of the same type, and the object is obtained according to the name

1. Change the name directly to the name stored in Spring.
insert image description here
2. Define the name through the @Qualifier annotation

insert image description here

  • Advantages: simple
  • Disadvantages:
    1. Unable to inject final modified variables. Because java stipulates that final modified variables can only be defined when they are initialized or defined in the constructor.
    2. It can only be used in the Ioc container.
    3. Does not conform to the single design principle.

2. Setter injection

Injection through the setter method also needs to set @Autowired.

insert image description here
If there are multiple objects of the same type, the acquisition method is the same as that of attribute injection, either directly changing to the name of the Bean object, or implementing it through the @Qualifier annotation.

  • Advantages: Usually Setter only sets one property, not multiple, so it conforms to the single design principle
  • Disadvantages:
    1. Unable to inject final modified variables.
    2. The object injected by the setter can be modified. Because the setter is originally a method that can be called and modified multiple times.

3. Constructor injection (official recommendation)

If there is only one constructor, the @Autowired annotation can be omitted.

insert image description here
insert image description here

  • Advantage
    1. Variables modified by final can be defined.
    2. The injected object will not be modified, because the constructor is only executed once.
    3. Constructor injection can ensure that the injected object is fully initialized.
    4. Better versatility, not limited to Ioc containers.

Summarize

The core functions of Spring are storing objects and reading objects.
There are two ways to store objects: 1. Add class annotations 2. Add method annotations.
The premise of the two methods is to add a scan directory. Starting from the added scan directory, scan annotations.
Read objects have dependency injection: 1. Property injection 2. Setter method injection 3. Construction method injection

Guess you like

Origin blog.csdn.net/m0_71690645/article/details/131818368