Spring basic concept and use


1. The concept of Spring

Spring is an open source framework and an IoC container that includes many tools and methods. Can be used to put Bean objects in and out.

1. Container

Containers I have touched before:
List/Map: data storage container.
Tomcat: Web container.

2.IoC

IoC (Inversion of Control) inversion of control, the right to create objects to the container, the instance of the object is no longer created by the caller, but by the container to create, the container will be responsible for controlling the relationship between programs, not by The caller's program code is directly controlled. The control right is transferred from the application code to the container, and the control right is reversed, which is the inversion of control.
Spring is also a container, an IoC (Inversion of Control) container.

3.OF

DI (Dependency Injection): The behavior/mechanism of dynamically introducing a class into the current class.

For example: constructing a car requires a frame, the frame requires a chassis, the chassis requires tires, and manufacturing tires requires knowing the size of the tires. If you need to change the size of the tires or other vertical properties, you need to change every object that depends on it, high coupling ; while the current method directly injects the tire object into the chassis, the chassis object into the frame, and the frame object into the car. When it is necessary to change attributes such as tire size, it only needs to be modified in the tire object, while the chassis and frame objects do not Another change is needed, which reduces the degree of coupling.
insert image description here

Previous method:insert image description here

Now method:
insert image description here

4. The relationship between Ioc and DI

IoC is a "goal" and a kind of thought, and DI is a specific realization. For example: Today I want to eat a good meal, this is a kind of goal and thought (IoC), and finally I have a barbecue today, this is DI.

2. Spring creation and use

1.Maven

insert image description here
insert image description here
insert image description here

2. Add Spring framework support

Inject dependencies in pom.xml and click Maven's refresh button.
insert image description here

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

    </dependencies>

Note: Domestic Maven source configuration

insert image description hereinsert image description here

3. Simple example

Create a normal class with a main method to run the Spring framework.

(1) Create a Bean object.

(2) Store the Bean object in Spring

a) Create a spring configuration file under resources.
insert image description here

spring-config.xml

<?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">
</beans>

b) Configure the Bean object into the spring configuration file.
insert image description here
insert image description here

(3) Read the Bean object from spring.

a) Get the Spring context object first.

method one:

//1.先得到 Spring 对象
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

Method 2: BeanFactory

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
The relationship between ApplicationContext and BeanFactory

The same points:
1. Both can get the Spring context object;
2. Both come from the top-level interface of Spring.
Differences:
1. Inheritance relationship and functions: ApplicationContext belongs to the subclass of BeanFactory; BeanFactory only has the most basic ability to access beans, while ApplicationContext includes more functions besides BeanFactory functions, such as: internationalization support, resources access, event propagation, etc.
2. Performance: The ApplicationContext loading method is to load the Bean object at one time, so it is very fast when accessing the Bean object later (hungry man mode); when the BeanFactory needs a Bean, it loads the Bean object, so when it executes the Bean acquisition, slower.

b) Take out the bean object from Spring

Method 1: Get the bean object according to the name (identity) of the bean

        //根据 bean 的名称(标识)获取bean对象
        User user = (User) context.getBean("user");//取user

Method 2: Get the bean according to the bean type

		//根据 bean 类型获取 bean,多个bean时会报错
        User user3 = context.getBean(User.class);

Method 3: Obtain beans according to bean name + bean type

		User user4 = context.getBean("user",User.class);

insert image description here
insert image description here

        //1.先得到 Spring 对象
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        //2.从Spring中取出bean对象
        User user = (User) context.getBean("user");
        //3.使用Bean(可选)
        System.out.println(user.sayHi());

insert image description here

4. Simply store objects in Spring

1. Five categories of annotations

Naming rules

insert image description here
Naming rules: If the first letter and the second letter are not capitalized, then name it as lowercase the first letter; otherwise, name it as the original class name.

Why are five class annotations needed?

(1) Through class annotations, users of the current class can be understood (for example: there is a geographical division before the license plate, etc.).
(2) The functions are slightly different.

Five categories of annotation uses (emphasis)

(1) @Controller (controller): It belongs to the business logic layer and is used to control user behavior. It is used to check the validity of user parameters.

(2) @Service (service): It belongs to the service layer and calls the persistent class to realize the response function. (Does not directly interact with the database, it is similar to the control center)

(3) @Repository (warehouse): It belongs to the persistence layer and directly interacts with the database. Usually, each table corresponds to a @Repository.

(4) @Configuration (configuration): It belongs to the configuration layer and is used to configure some information of the current project.

(5) @Component (component): It belongs to the public tool class and provides some public methods.

注:@Component是除了它自己的其他四个类的父类。

2. Method annotation

Save the object to Spring Method 2.

@Bean

@Bean: Store the method object of the currently modified method in Spring.
(1) @Bean should be used in conjunction with the five major categories;
(2) If the injected bean is not named when obtaining the bean, it will be obtained directly by the method name; if the name attribute is used for naming, it needs to be obtained by the set method name .
(3) After the name attribute is set for @Bean, the original method name of the experiment cannot obtain the object, and can only be obtained by using the set name.
insert image description here
insert image description here

注:@Bean注解一定要配合5大类注解一块使用,否则是无效的方法注解。

5. Easier Object Injection

@Autowired
@Resource

1. Property injection

Advantages of using property injection to obtain beans
insert image description here
: simple implementation.
Disadvantages:
       (1) An immutable (final) object cannot be injected. Generally, properties modified by final are either assigned directly or initialized in the constructor.
       (2) Applicable only to IoC containers.
       (3) It is easier to violate the principle of singleness. (For the class level, the writing method is simple and it is easier to make mistakes)

2. Setter injection

insert image description here

Advantages: more in line with the single design principle. (For the object method level, the writing method is troublesome, and it will be written only when it is used)
Disadvantages:
       (1) Immutable objects cannot be injected.
       (2) The injected object can be modified. (Since the set method is an ordinary method and can be called repeatedly, there is a danger of being modified when it is called)

3. Construction method injection

Constructor injection is the injection method officially recommended by Spring since 4.x.

insert image description here

Advantages:
(1) An immutable object can be injected.
(2) The injected object will not be modified.
         a) The final modifier is added.
         b) The construction method is executed only once as the class is loaded (unlike the risk that set may be modified multiple times)
(3) The injected object will be fully initialized.
(4) Better versatility.

Summary: In daily development, it is still the mainstream way to use attribute injection to realize easier reading of beans.

Relationship between @Autowired and @Resource

The same point: they are all used to implement dependency injection.
Differences:
       (1) Different functional support: @Autowired supports attribute injection, setter injection, and constructor injection; @Resource supports attribute and setter injection, but does not support constructor injection.

       (2) Different origins: @Autowired comes from the Spring framework; and @Resource comes from JDK.

       (3) Parameter support is different: @Resource supports more parameter settings; while @Autowired only supports required parameters.

1. The property injection of @Resource is compared with the property injection of @Autowired:
insert image description here
2. The setter injection methods are similar.

6. The scope of Bean and the life cycle of Spring

1.Bean scope

Bean scope: A certain behavior pattern of Bean in the entire Spring framework (project).

Lombok

lombok: A tool that simplifies Java development, an implementation tool that replaces the necessary code in Java more easily.
Use of lombok:
1. Reference lombok in the project.
(1) Add dependencies in pom.xml.

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
      

(2) Download the lombok plugin in setting->plugingz.

insert image description here
@Data==>@Setter+@Getter+@ToString

Bean scope classification

(1) singleton: singleton mode. (default scope) scoped to the IoC container.
The default scope of UserBean is @Scope("singleton")
insert image description hereinsert image description here
(2) prototype: Prototype mode (multiple instance mode)
@Scope("prototype")
insert image description here
(3) request: request scope.
(4) session: session scope. -> Similar to ThreadLocal in multithreading
(5) application: global scope. It acts on the servlet container and is applied in Spring MVC.
(6) websocket: Applied in Spring WebSocket.

2. Spring execution process

(1) Start the container (startup project)
(2) Read the configuration file and initialize.
        a) use xml to directly register beans;
        b) configure beans and (scan) paths.
(3) Store beans in spring, scan and assemble them through class annotations.
(4) Read the bean from spring and assemble it into the corresponding class.

3. Bean life cycle

The life cycle refers to the entire life process of an object from birth to destruction. We call this process the
life cycle of an object. Bean's life cycle is divided into the following 5 parts: Insert code slice here
(1) instantiate (corresponding to "loading" in JVM), from scratch, convert bytecode into object in memory, just allocate Memory.
(2) Set properties (Bean injection and assembly)
(3) Initialization:
        a) Various notifications;
        b) Pre-initialization work;
        c) Initialization work (use annotation @PostConstruct initialization, use (xml) init-method initialization );
        d) Post work for initialization.
(4) Use Bean;
(5) Destroy Bean.
insert image description here
Instantiation - "Set Properties - "Initialization
insert image description here

Guess you like

Origin blog.csdn.net/qq_45283185/article/details/129353339