Use and basic principles of Spring

Keywords: Spring

3. Send the Ioc of Spring

  1, Preliminary knowledge: Reflection

1. Basic concept of reflection

​     During operation, the basic information of the class (class properties, class construction methods, and class general methods) is dynamically obtained

  2. Use of reflection

​     (1) Three ways to get Class objects

package org.test;

import org.lanqiao.Student;

import java.lang.reflect.*;

public class Test {

    public static void getClassInfo(String className) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
        //The first method is to obtain the class object through the class. Class
        //Class c = Student.class;
        //The second way: through forName()
        //Class c = Class.forName(className);
        //The third way: get class information through class objects
        Student student = new Student();
        Class c = student.getClass();

        //Gets the properties of the class
/*        Field[] fields = c.getFields(); //Get the class and all public properties inherited from the parent class (excluding private properties)
        for (Field field : fields) {
            System.out.println(field.getName());
            System.out.println(field.getType());
            System.out.println(Modifier.toString(field.getModifiers()));
        }*/
        //Get all the properties defined by this class
       Field[] declaredFields = c.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField.getName());
            System.out.println(declaredField.getType());
            System.out.println(Modifier.toString(declaredField.getModifiers()));
        }
        declaredFields[0].setAccessible(true);//Brute force access to private variables
        declaredFields[0].set(student,"Zhao Liu");

        System.out.println(student.getName());
        //Constructor[] constructors = c.getConstructors();
        /*for (Constructor constructor : constructors) {
            System.out.println(constructor.getName());
            System.out.println(constructor.getParameterCount());
            Parameter[] parameters = constructor.getParameters();
            for (Parameter parameter : parameters) {
                System.out.println(parameter.getName()+","+parameter.getType());
            }
        }*/
       /* Constructor constructor = c.getConstructor(int.class, String.class, int.class);
        Student student2 = (Student) constructor.newInstance(180,"Zhang San ", 21);
        System.out.println(student2);
        *//*System.out.println(student.getName());*//*
        Method method = c.getMethod("study", String.class);
        method.invoke(student2,"Wang Wu ");*/
       /* Method[] methods = c.getMethods();
        for (Method method : methods) {
            System.out.println(method.getReturnType());
            System.out.println(method.getName());
        }*/
     /*   Method[] declaredMethods = c.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println(method.getReturnType());
            System.out.println(method.getName());
        }
         declaredMethods[4].invoke(student,"Li Si ");*/
        //System.out.println(o);
    }


    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException , NoSuchMethodException {
       getClassInfo("org.lanqiao.Student");
    }
}

  2, Basic concepts of Spring framework

1. Basic concepts of spring

Spring is an open source framework, which is developed by [rod Johnson]( https://baike.baidu.com/item/Rod Johnson) Create. It is created to solve the complexity of enterprise application development. Spring uses basic JavaBean s to do things that could only be done by EJB s before. However, the purpose of spring is not limited to server-side development. From the perspective of simplicity, testability and loose coupling, any Java application can benefit from spring.

Spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework.

###2. The role of spring

IoC provides loose coupling and decoupling

package org.test;

import org.lanqiao.IHello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        IHello hello = (IHello) applicationContext.getBean("hello");
        hello.sayHello();
    }
}
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--entrust Spring IoC Create and manage the container bean Object of -->
    <bean id="hello2" class="org.lanqiao.Hello"></bean>
    <bean id="hello" class="org.lanqiao.Hello2"></bean>
    <bean id="student" class="org.lanqiao.Student"></bean>
</beans>

   3, Ioc of Spring

1. Concept of IOC control inversion

IoC   Inverse of Control   Control reversal

The method of creating objects is handed over to the Spring Container container in the code

The creation, use and destruction of bean s are all handled by the IoC container

2.Bean life cycle

<bean id="hello2" class="org.lanqiao.Hello" init-method="init" destroy-method="d"></bean>

(1) Create

​     A single instance mode in which bean s are instantiated as soon as the ioc container is started

​     One is that the ioc container is not created when it is started, but only when the object is called

(2) Initialization  

init-method="init"

(3) Use

Call the normal method of the bean

(4) Destroy

Destroy method is not directly removed from memory, but marked to inform GC to recycle

###3. Scope of bean

scope:  

Singleton: singleton (default)

Prototype: prototype (multiple cases)

In web applications:

scope="request"

scope="session"

scope="application"

Difference between single case and multiple cases:

(1) Single instance means that there is only one object in the IOC container, and there will be multiple objects in the multi instance mode

(2) The singleton mode will be created as soon as the ioc container is started, and the multi instance mode will be created only when it is used

​​​​​​​

4, DI for Spring

DI dependency injection dependency injection, which assigns a value to the object of the created bean

(1) According to the way of dependency injection

  1. Attribute injection method

<bean id="student" class="org.lanqiao.Student">
        <!--Dependency injection-->
        <property name="id" value="1"/>
        <property name="name" value="Zhang San"/>
        <property name="age" value="21"/>
    </bean>

2. Construction method and injection mode

It can be injected through the parameter name, parameter index and parameter type of the construction method. It is recommended to use the parameter name (intuitive)

<!--Student student01 = new Student(2,"Li Si",21);-->
    <bean id="student01" class="org.lanqiao.Student">
        <constructor-arg name="id" value="2"/>
        <constructor-arg name="name" value="Li Si"/>
        <constructor-arg name="age" value="21"/>
        <!--<constructor-arg index="0" value="2"/>
        <constructor-arg index="1" value="Li Si 2"/>
        <constructor-arg index="2" value="23"/>-->
    </bean>

  3. Injection through the factory

The function of factory is to produce objects. You can do other things while creating objects

 <!--Use non static factory-->
    <bean id="studentFactory" class="org.lanqiao.factory.StudentFactory"/>
    <bean id="student02" factory-bean="studentFactory" factory-method="create"/>
    <!--Use static factory-->
    <bean id="student03" class="org.lanqiao.factory.StudentFactory2" factory-method="create"/>

4. Use spiel (spring expression language) #{} to support expressions

<bean id="student04" class="org.lanqiao.Student">
        <!--attribute SpEL Dependency injection, call setXXX()-->
        <property name="id" value="#{1}"/>
        <property name="name" value="#{'three'} "/ >
        <property name="age" value="#{10+10}"/>
</bean>

5. How to use the P namespace

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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">
    <!--use p Namespace -->
    <bean id="student05" class="org.lanqiao.Student" p:id="5" p:name="Sun Qi" p:age="22"/>
</beans>

According to the type of attribute value

1. Injection of basic data types

 <bean id="student" class="org.lanqiao.Student">
        <!--Dependency injection-->
        <property name="id" value="1"/>
        <property name="name" value="Zhang San"/>
        <property name="age" value="21"/>
    </bean>

  2. Reference data type

<bean id="grade" class="org.lanqiao.Grade">
        <property name="id" value="1"/>
        <property name="gname" value="Freshman"/>
</bean>
<bean id="student06" class="org.lanqiao.Student">
        <property name="id" value="1"/>
        <property name="name" value="Zhang San"/>
        <property name="age" value="21"/>
        <property name="grade" ref="grade"/>
</bean>

3. null value injection

  <bean id="student07" class="org.lanqiao.Student">
        <property name="id" value="1"/>
        <property name="name" value="Zhang San"/>
        <property name="age" value="21"/>
        <property name="grade">
            <!--Inject null-->
            <null></null>
        </property>
    </bean>

(3) Spring auto assembly

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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"
       default-autowire="byType">

    <bean id="grade" class="org.lanqiao.Grade">
        <property name="id" value="1"/>
        <property name="gname" value="Freshman"/>
    </bean>
    <bean id="student" class="org.lanqiao.Student">
        <property name="id" value="1"/>
        <property name="name" value="Zhang San"/>
        <property name="age" value="21"/>
    </bean>

The setting of default autowire = "bytype" here means that there is a Grade attribute in the student bean that has not been declared and injected. The type matching this attribute will be automatically found in the Spring IoC container. If the types are consistent, the value in the container will be injected into this attribute
byType cannot have duplicate type beans in IoC, which will cause confusion. I don't know which bean to inject
byName is automatically injected into bean s with the same property name
This setting is global. The whole IoC container will be automatically assembled according to type or name. This method is risky and is not recommended
 

Posted by -entropyman on Sat, 20 Nov 2021 09:33:46 -0800