Spring detailed

Article Directory


1 Spring concept

1. Concept

1. Spring is a lightweight open source JavaEE framework.
2. Spring can solve the complexity of enterprise development.
3. Spring has two cores:
IoC (Inversion of Control) : The process of creating objects is handed over to Spring for management, and there is no need to create objects with new.
AOP (Aspect Oriented) : Function enhancement without modifying the source code.

2. Features

1. Convenient decoupling (IoC) and simplified development (IoC)
2. Support for AOP, can enhance functions without changing the source code
3. Support Junit to facilitate program testing
4. Convenient integration with other frameworks
5. Reduce the difficulty of using JavaEE, Such as JDBC, JavaMail, remote call
6, convenient transaction operation
7, Java source code learning specification

3. Create a Spring project

1. Introduction to the jar package to be imported

1. The core part of Core Container is the necessary jar package
2. Commons-logging

Insert picture description here

2. The dependencies that need to be introduced

Insert picture description here
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.7</version>
        </dependency>
        <!-- 4.Spring test依赖:方便做单元测试和集成测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

3. Configuration file bean.xml

Create a Spring configuration file in xml format, and configure the created objects in the configuration file.

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

    <!--配置User对象创建-->
    <bean id="user" class="com.ll.spring.User"></bean>
</beans>

4. Unit testing

    @Test
    public void testAdd(){
        // 1.加载Spring配置文件
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        // 2.获取配置创建的对象,user就是通过Spring创建的对象
        User user = context.getBean("user", User.class);
        // 3.调用方法
        user.add();
    }

5. Project structure

Insert picture description here

2 IoC container

1. Basic concepts of IoC

1. Inversion of control, the creation of our objects and the process of direct invocation of objects are handed over to Spring for management.
2. Using IoC is for decoupling

2. The underlying principle of IoC

1. The xml configuration file, configure the objects that need to be created

<bean id="user" class="com.ll.spring.User"></bean>

2. There are service and dao classes, and then create a factory class
to introduce the factory model

3. Obtain the bytecode file of the class by reflection, and create the object through reflection

public class UserFactory {
    public static UserDao userDao(){
        // 1、通过xml得到class="com.ll.spring.User"
        String classValue=class属性值;
        // 2、通过反射创建对象
        Class clazz = Class.forName(classValue);
        // 3、创建对象,反射无参的构造器,需要构造器可见;
        return (UserDao)clazz.newInstance();
    }
}

3. IoC interface (BeanFactory)

The idea of ​​IoC is based on the IoC container, and the bottom layer of the IoC container is the object factory.

1. Spring provides two ways to implement the IoC container

1.BeanFactory

The basic implementation of the IoC container is an interface used internally by Spring. It is not provided to developers
when the configuration file bean.xml is loaded. Objects will not be created. Objects will be created when objects are used.

BeanFactory context=new ClassPathXmlApplicationContext("bean.xml");

2.ApplicationContext

The sub-interfaces of the BeanFactory interface provide more and more powerful functions and are generally used by developers.
When the configuration file is loaded, the object will be created
. This method is commonly used. We will process the time-consuming and resource-consuming operations when the project starts, and create the object during the startup process. When the server starts, it executes the code, loads the configuration file, and creates the object. The process is completed when the server starts, and the time-consuming and resource-consuming process is handed over to the server.

ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");

4. Principle of IoC Operation Bean

1. What is Bean Management

1. Spring creates objects
2. Spring attributes are injected into
the private String name of the bean class;
get() and set() methods

2. Two ways of Bean management operation

1. Based on xml

1. Spring creates objects

1. In the Spring configuration file, you can create objects by experimenting with bean tags and adding object attributes to the tags.
2. Commonly used attribute
id: the unique identifier of the object
class: the full path of the class (package class path)
3. When creating an object, the default construction method is also executed without parameters. (If the class contains a parameter constructor, the parameterless constructor must be explicitly declared)

2. Spring attribute injection

DI (Dependency Injection): It is a specific implementation in IoC, which is to inject attributes.

private String name; set the value in name
1, use the set method to inject

    <bean id="user" class="com.ll.spring.User">
        <property name="name" value="张三"></property>
    </bean>

2. Parameterized structure injection

    <bean id="user" class="com.ll.spring.User">
        <constructor-arg name="name" value="张三"></constructor-arg>
        <!--<constructor-arg index="0" value="张三"></constructor-arg>-->
    </bean>
3. Springxml automatic assembly

In practice, xml automatic assembly is used less, and annotation automatic assembly is used more.

Manual assembly: <property name="name" value="Zhang San"></property>
According to the specified assembly rules (property name or property type), Spring will automatically inject the matching property value.

Two ways of automatic assembly:
1. Attribute name assembly autowire="byName", the id of the Bean must be the same as the class attribute name
2. Attribute type assembly autowire="byType", there can be no two identical Bean id

4. External properties file
1. Directly configure the database connection pool
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1/db_student?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
2. External property file configuration
//   jdbc.properties
prop.driverClassName=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://127.0.0.1/db_student?serverTimezone=UTC
prop.username=root
prop.password=123456
<?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
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--在Spring配置文件中实验标签引入外部配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClassName}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.username}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>
</beans>

2. Based on annotations

1. Spring creates objects
2. Spring attribute injection

3.FactoryBean

Spring has two types of beans

One is ordinary Bean: what type is defined in the configuration file will return what type.
There is also a FactoryBean: the type returned by FactoryBean can be different from the one defined in the configuration file.
1. Create a class. This class is used as a factory bean to implement FactoryBean.
2. Implement the methods in the interface, and define the returned Bean type in the implemented method.

public class MyBean implements FactoryBean<User> {
    // 定义返回Bean
    public User getObject() throws Exception {
        User user = new User();
        user.setName("张三");
        return user;
    }

    // 返回类型
    public Class<?> getObjectType() {
        return null;
    }

    // 单例
    public boolean isSingleton() {
        return false;
    }
}
<!--bean.xml-->
<bean id="bean" class="com.ll.factory.MyBean"></bean>
    @Test
    public void test1(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        // 注意这里是User.class而不是MyBean.class
        User bean = context.getBean("bean", User.class);
        System.out.println(bean);
    }

4. Bean scope

1. In Spring, you can set whether the created Bean instance is single-instance or multi-instance.
2. Single-instance objects are created by default.
3. Set whether the Bean is single-instance or multi-instance.

Scope setting:
singleton means single instance, singleton will create single instance object when loading Spring configuration file. ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
Prototype means multi-instance, and multi-instance object is created when the getBean method is called. User user = context.getBean("user", User.class);
request, session

5. Bean's life cycle

Life cycle: the process from object creation to object destruction.

1. Basic method

1. Create a Bean instance through the constructor (no parameter construction)
2. Set values ​​for bean attributes and reference to other Beans (call the set method)
3. Call the initialization method of the Bean (configuration is required)
4. The Bean can be used (The object is obtained)
5. When the container is closed, call the destruction method of the Bean (the method that needs to be configured to be destroyed)

    <bean id="user" class="com.ll.spring.User" init-method="initMethod" destroy-method="destroyMethod">
        <property name="name" value="张三"></property>
    </bean>
public class User {
    private String name;

    public User() {
        System.out.println("1、通过构造器创建Bean实例(无参构造)");
    }

    public void setName(String name) {
        System.out.println("2、为bean的属性设置值和对其他Bean引用(调用set方法)");
        this.name = name;
    }

    // 创建执行的初始化方法
    public void initMethod(){
        System.out.println("3、调用Bean的初始化的方法(需要进行配置)");
    }

    public void destroyMethod(){
        System.out.println("5、当容器关闭的时候,调用Bean的销毁方法(需要进行配置销毁的方法)");
    }
}

2. Bean post-processing implements the BeanPostProcessor interface

1. Create a Bean instance through the constructor (no parameter construction)
2. Set values ​​for bean properties and reference to other Beans (call the set method).
Pass the Bean instance to the Bean post processor.
3. Call the Bean initialization method. (Need to be configured)
The method of passing the Bean instance to the Bean post processor
4. The Bean can be used (the object is obtained)
5. When the container is closed, the Bean's destruction method is called (the method of configuration destruction is required)

<bean id="myBeanPost" class="com.ll.spring.MyBeanPost"></bean>
public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化前执行的方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化后执行的方法");
        return bean;
    }
}

3 Aop

4 JdbcTemplate

5 Transaction Management

6 New Features of Spring5