Spring IOC DI theory and coding implementation of 16,000 words-idiots can understand!

 Before we talk about Spring, let’s take a brief look at the development and evolution of JavaEE in web applications.

1. Initially, Java used the Servlet+Html solution for web application development. Whether it is a beginner or a senior technical expert, anyone who has gone through this stage will feel that all logic is controlled by Servlet, and HTML is used for pages. Display, this method is extremely troublesome in the case of maintenance and demand changes

2. Later, in order to simplify the development, the developers upgraded the Servlet, so Jsp was derived, but Jsp essentially mixes java code in Html pages. It is only suitable for applications with simple business processes. If the system is complex, Jsp code is seriously lacking in readability, page display and business logic are mixed, and maintenance is still very difficult!

3. Later, in order to solve the program readability and maintainability, Sun used Jsp+JavaBean to develop Web applications. The former is responsible for page display, and the latter is responsible for business logic. It seems that the division of labor is clear and each performs its own duties. To a certain extent It does improve the readability and maintainability of the program, but this development model still has shortcomings, that is, Jsp will display and process control together, on the one hand, it greatly increases the complexity of the product, deployment There is a certain degree of difficulty in getting it up; in addition, in terms of efficiency, due to the mixing of a large amount of Jsp code in Jsp, it still needs to be converted into a .java file during execution, and then a .class bytecode file is generated, and it is finally run. Obviously this process It is more complicated. Moreover, if there is an error in this process, the error refers to the java file instead of the Jsp itself, then there is no parsing process from the Jsp to the .java file in the middle, which is very painful during debugging. Yes, this mode is only suitable for the rapid construction and operation of small projects

4. Then Sun company upgraded again, introduced the MVC thinking model, using JSP + Servlet + JavaBean to develop Web applications. JSP is responsible for page display, Servlet is responsible for process control, and JavaBean is responsible for business logic. The classification of web application development has become clearer. Obviously, this idea of ​​MVC is still very fragrant. Until now, almost all framework technologies follow the MVC design idea, but this model is still not a more standardized development model. Programmers cannot evaluate the development cycle, and it is difficult to control time efficiency well.

5. With the progress of the times, a mature MVC development framework is also born-that is Struts. For some large-scale projects, the Struts framework will improve development efficiency and have great benefits for later maintenance

M: Usually use other model components in Structs to implement business logic, such as: JavaBean technology, EJB technology, Hibernates design pattern

V: Mainly composed of JSP pages, but also include HTML documents, standard tag libraries (JSTL) and Struts tag libraries, JavaScript scripts and CSS styles, multimedia files, message resource files, and ActionForm classes

C: ActionServlet component: the central controller of the Struts framework, RequestProcessor component: the request processor of each sub-module, Action component: business agent, it will call the model for a specific business logic processing

Nowadays, the development of JavaEE on Web applications has developed to a very mature stage. Today I will talk about the hot core technology framework-Spring

Isn't EJB very fragrant? Why do we need Spring?

Although EJB solves the business logic problems of developers to a large extent, in terms of logic, EJB itself is too complicated and bloated, and its operating environment is also more demanding. If you understand the fat friends of EJB You will know that to use EJB to develop on the Web side, you must first implement the interfaces provided by WebSphere, WebLogic, JBoss and other servers before it can run on the corresponding server. In terms of flexibility, it has limitations. In addition, these three servers Only JBoss is open source. I believe that this will filter out many people who want to use it. After all, open source now rules the world!

The second is that when using EJB, our code portability is extremely poor. As mentioned earlier, if EJB wants to run on a server that supports it, it must first implement the corresponding interface. If I say, I don’t want to run on WebLogic now. , Change to a Tomcat, obviously the latter does not support the former

So in general, EJB can be said to be a very heavyweight technical framework. Nowadays, most of the society is the development of projects with complicated business and changing needs, so it is obviously difficult to satisfy

What are the benefits of having said so much about Spring? Is it that fragrant?

Let me start with a tall word: Spring is a lightweight JavaEE solution that integrates many excellent design patterns

First of all, relative to most of the troubles and limitations mentioned in the previous development history of Spring, it can be solved very well. The most important point is that Spring is open source, just when EJB is mixed in the circle. When the water rose, the weak and helpless Spring chose to open source and praised some popularity for itself. After all, most of the excellent frameworks are charged. It is good for large companies, but it is difficult for small companies to pay huge fees. Just like this, Spring Gradually it has been recognized by small and medium-sized companies, because Spring provides a lot of interfaces for integrating third-party frameworks, and gradually formed a clear stream of Spring + Struts + Hibernate in the circle , which is the famous SSH, and later appeared after several twists and turns. SSM (I mainly talk about Spring here, you need to Baidu for details)

 

Okay, let’s talk about Spring officially

 

Speaking of Spring, we must talk about it from several core technologies-IOC, DI, AOP

IOC-Inversion of Control, literally translated as Inversion of Control

What is control? What is reversal?

There is a popular saying in the kingdom of Java-everything, everything is an object

control:

In the traditional mode, the creation, management, and destruction of objects are all controlled by those who need them (also objects). The so-called control is the right to control their own members.

Reverse:

Reversing in Spring is to give up this control, give this right to Spring, let Spring help us create, manage, and destroy objects, we just need to use it

to sum up:

Inversion of control:

The program gives up the right to create, manage, and destroy objects, and leave this right to Spring to manage, when we need it, we only need to use it from Spring

DI-Dependency Injection, literally translated as dependency injection

Why do we need to rely on?

When object A completes some functions, it needs some external resource object B to help itself to complete it together. If necessary, it will have dependency, that is, object A depends on object B.

Who depends on whom?

Of course, external classes depend on internal member attributes! as follows

class A{
   B
   C
   D
  ...
}
此时,类A依赖内部成员属性 B C D ...

Who injected whom?

Obviously our IOC container injects resource objects into the objects needed for these objects

What is injected?

Inject what the external class or object needs. Such as resources, objects, data, etc.

The principle of Spring implementation:

Through the reflection of Java, all attributes and methods of the class can be obtained, and then the relationship between the class and the class can be described through the configuration file (xml) or annotation, and then it can be managed

what is the benefit?

1. Decoupling

2. Manage through a third party, only need to modify the third party data to manage the relationship between objects, easy to maintain

3. No need to create the same object multiple times, saving resources

 

Having said so many principles, is it annoying to listen, then just come to the code!

上代码之前我们先来了解一下怎么来创建一个实例对象

1.————>从本地或者网络上加载.class文件(方法区)
2.————>根据.class文件创建java.lang.class对象(JVM)
3.————>再根据.class对象模板来创建实例对象(堆)


了解了如何创建对象,我们再来看常见的创建对象的方式有哪些
1.通过new关键字来创建对象
2.通过反射机制获取类的全限定类名,在运行时获取对象的所有属性及方法

(这里为了研究我们暂时只说这两种创建对象的方式,也是日常常用到的方式,需要了解其他方式的自行百度)

In daily development, if we need to complete a function, first we need to have an interface and implementation class

#接口

package com.xiaozhao.spring.service;

import com.xiaozhao.spring.entity.Student;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/15 16:44
 */
public interface StudentService {
    public Student login(String user, String password);
}



#实现类

package com.xiaozhao.spring.service.impl;

import com.xiaozhao.spring.service.StudentService;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/16 16:02
 */
public class StudentServiceImpl implements StudentService {

    @Override
    public Student login(String user, String password) {
        System.out.println("调用此方法!");
        return null;
    }
}

Then by creating the implementation class, call the method inside to complete the operation

package com.xiaozhao.spring;


import com.xiaozhao.spring.service.StudentService;
import com.xiaozhao.spring.service.impl.StudentServiceImpl;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/15 16:36
 */
public class Demo {
    public static void main(String[] args) {
        StudentService studentService = new StudentServiceImpl();
        studentService.login("xiaozhao","123456");
    }
}

operation result:

D:\Environment\Java\jdk1.8.0_251\bin\java.exe "...

调用此方法!

Process finished with exit code 0

Problems in creating objects in traditional mode:

1. There is a coupling between objects, and the new keyword is needed for strong association. The change of one will affect the other

2. Hard-code the implementation class of the interface in the program through new

3. Not conducive to code maintenance

 

The way Spring creates objects :

                      Created based on the factory design pattern

Simple factory model:

package com.xiaozhao.spring.factory;

import com.xiaozhao.spring.service.StudentService;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/16 16:23
 */
public class BeanFactory {
    private static Properties pro = new Properties();
    static {
        try {
            //通过读取applicationContext.properties文件获取流
            InputStream inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
            //从流中获取key-value对
            pro.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static StudentService getStudentService(){

        StudentService studentService = null;
        try {
            //根据value(全限定类名)通过反射机制创建class对象
            Class clazz = Class.forName(pro.getProperty("studentService"));
            //通过class对象创建实例对象
            studentService = (StudentService) clazz.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        //返回所需实例对象
        return studentService;
    }
}

Here we need to configure the key-value pairs of the objects we need to create in the applicationContext.properties file

studentService=com.xiaozhao.spring.service.impl.StudentServiceImpl

Create an instance object in the test class Demo through the static method of the factory class BeanFactory

package com.xiaozhao.spring;


import com.xiaozhao.spring.factory.BeanFactory;
import com.xiaozhao.spring.service.StudentService;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/15 16:36
 */
public class Demo {
    public static void main(String[] args) {
        StudentService studentService = BeanFactory.getStudentService();
        studentService.login("xiaozhao","123456");
    }
}

operation result:

It can be seen here that we can also create instance objects of the implementation class through the factory, so what are the benefits?

1. Decoupling, we no longer use the new keyword for strong association in the test class Demo. If you add new methods or delete some methods in StudentServiceImpl, as long as the new method is not involved, the caller will not be affected. , Even if you need to use the new method, you can call it directly, that is, the caller only needs to pay attention to what his business needs and call the method with the function, no longer subject to additional influence

2. Easy to maintain, if one day we don’t want the StudentServiceImpl object, we only need to re-create a new implementation class, configure the properties file and modify the value of the key to get any object

3. The strong association of the new keyword is no longer needed in our test code

Thinking: This kind of factory still has shortcomings. If we need other instance objects, do we still need to modify the XXX getXXX method in the factory class? Is there a general method that will return us whatever we want? What about the object?

That works! Let's transform the factory class

package com.xiaozhao.spring.factory;


import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/16 16:23
 */
public class BeanFactory {
    private static Properties pro = new Properties();
    static {
        try {
            //通过读取applicationContext.properties文件获取流
            InputStream inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
            //从流中获取key-value对
            pro.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String key){

        Object ret = null;
        try {
            //根据value(全限定类名)通过反射机制创建class对象
            Class clazz = Class.forName(pro.getProperty(key));
            //通过class对象创建实例对象
            ret = clazz.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        //返回所需实例对象
        return ret;
    }
}

After the transformation, how do we create an instance of StudentService?

package com.xiaozhao.spring;


import com.xiaozhao.spring.factory.BeanFactory;
import com.xiaozhao.spring.service.StudentService;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/15 16:36
 */
public class Demo {
    public static void main(String[] args) {
        StudentService studentService = (StudentService) BeanFactory.getBean("studentService");
        studentService.login("xiaozhao","123456");
    }
}

Let's modify the sentence printed in StudentServiceImpl

package com.xiaozhao.spring.service.impl;

import com.xiaozhao.spring.entity.Student;
import com.xiaozhao.spring.service.StudentService;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/16 16:02
 */
public class StudentServiceImpl implements StudentService {

    @Override
    public Student login(String user, String password) {
        System.out.println("调用此方法!11111");
        return null;
    }
}

Try it out

No problem at all, what if we want other implementation objects? no problem! Still Very Easy.!

步骤:
1.创建接口
2.实现接口
3.配置properties文件
4.测试类中传入相应的key值

#接口

package com.xiaozhao.spring.service;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/16 17:28
 */
public interface UserService {

    public void register();
}


#实现类

package com.xiaozhao.spring.service.impl;

import com.xiaozhao.spring.service.UserService;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/16 17:28
 */
public class UserServiceImpl  implements UserService {
    @Override
    public void register() {
        System.out.println("我是新对象!!!");
    }
}


#修改properties配置文件

userService=com.xiaozhao.spring.service.impl.UserServiceImpl

#测试类中传入相应的key,并调用相应方法

 UserService userService = (UserService) BeanFactory.getBean("userService");
 userService.register();

Take a look at the structure:

operation result:

Although hard, but we finally understand a simple pattern of using factories to create objects

 

Use the factory design pattern to create instance objects for us

      benefit:

             1. Avoid the strong association of new keywords

             2. Make the code easy to maintain, dissatisfied with the original object, only need to pay attention to the design of the new object, no need to modify the original object (open and close principle)

             3. Decoupling

      to sum up:

             The essence of Spring: ⼯⼚ ApplicationContext (applicationContext.xml)

In fact, the underlying design thinking of our Spring is also designed according to this idea. Of course, the Spring factory must be more powerful than our perfect function, and the design complexity is incomparable, but it is inseparable. Qizong is based on this idea!

 

Well, understand the essence of Spring, then we start to get our first Spring program!

环境:
    1.JDK————1.8
    2.IDEA————2020.1.3
    3.Maven————3.6+
    4.SpringFramework————5.0+
1.引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xiaozhao</groupId>
    <artifactId>Spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
    </dependencies>


</project>

effect:

We create a configuration file through Spring Config, named applicationContext.xml (the previous configuration file is applicationContext.properties)

After preparing the environment and configuration files

                    Let's think about a question-what is the difference between ordinary Java objects and Spring Beans? Is it the same?

Don’t know it’s okay, let’s create a Spring Bean first

步骤:
    1.在applicationContext.xml文件中告诉Spring有哪些类需要被创建
    2.在测试类中调用Spring的核心接口方法getBeanl()来获取Spring Bean


#在applicationContext.xml文件中告诉Spring有哪些类需要被创建

    <bean id="userService" class="com.xiaozhao.spring.service.impl.UserServiceImpl"/>

#在测试类中调用Spring的核心接口方法getBeanl()来获取Spring Bean

public class Test {
    public static void main(String[] args) {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.register();
    }
}

Interruption:

The getBean() method of the factory object has such multiple loads. When passing in the corresponding parameters, you must pay attention to the parameter type and the meaning of each overload

example:

//通过这种⽅式获得对象,就不需要强制类型转换
Person person = ctx.getBean("person", Person.class);
System.out.println("person = " + person);
 
//当前Spring的配置⽂件中 只能有⼀个<bean class是Person类型
Person person = ctx.getBean(Person.class);
System.out.println("person = " + person);


..............

Spring core interface ApplicationContext provides

ClassPathXmlApplicationContext, XmlWebApplicationContext and AnnotationConfigApplicationContext three creation factory classes

the difference:
 
⾮web环境 : ClassPathXmlApplicationContext (main junit)
web environment : XmlWebApplicationContext
Annotation development: AnnotationConfigApplicationContext
 
 
In order to distinguish the previous output, I changed the output statement of UserServiceImpl, the effect of running is as follows
 
In this way, we got a Spring Bean
 
 
Okay, after a meal, let's look back at the thoughts we left above- the difference between Java objects and Spring Beans
 
Java objects:
              Objects created by Java code can be:
                                       1.new keyword
                                       2. Reflection-Class.forName ("fully qualified class name") or the newInstance () instance method of the java.lang.reflect.Constructor class.
                                       3. Call the clone() method of the object
                                       4. Use deserialization to call the readObject() method of the java.io.ObjectInputStream object
Spring Bean:
              Spring Bean is also a Java object, but it has to go through the processing of Spring factory, so it is called Spring Bean
 
So here comes the problem!
 
What is Spring's processing of Java objects? What are the processing steps? What has been processed?
 
简述Spring Bean的过程:
        1.通过构造函数或者Set的方式进行对象的构建
        2.将依赖的成员属性或者对象进行注入
        3.调用BeanPostProcessor接口的实现类,在对象初始化前进行额外功能的加工
        4.Spring对对象进行初始化操作
        5.可以进行人工初始化(一般选择不进行人工初始化)
        6.调用BeanPostProcessor接口的实现类,在对象初始化后进行额外功能的加工
        7.创建完成,返回创建好的对象

Through the above process, we learned that Spring performs a series of processing on our Java objects

    The answer to the above question can be solved:

                             Spring's processing of Java objects is divided into 7 steps, the purpose is to add additional extended functions to Java objects (logging, transaction, performance testing...)

note:

ApplicationContext⼯⼚的对象占⽤⼤量内存
不会频繁创建对象 : ⼀个应⽤只会创建⼀个⼯⼚对象
ApplicationContext⼯⼚:⼀定是线程安全的(多线程并发访问)

Let's walk through the process of using spring development

1. 创建类型

2. 配置配置文件 applicationContext.xml

3. 通过⼯⼚类,获得对象

 ApplicationContext
         |
    接口的实现类
         |
 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");

In actual development, we often refer to the objects created by Spring as beans or components (componet)

      Some methods of Spring factory:

                       getBeanDefinitionNames ()---->Get the names of all the beans in the spring factory, and return a String[] array

                       getBean("class name", class.getClass())---->The object returned by the method does not need to be cast

                       containsBeanDefinition ( "the id value of the configuration file bean" ) ----> Determine whether the Spring bean with the specified id is included

                       getBeanNamesForType(Class.getClass())------>Get the corresponding id value in the configuration file according to the type, and the return is a string array

                       .........

Okay, there are new questions

Now that we have such a good Spring factory, can we hand over all the beans to the Spring factory for management? Are there any exceptions?

the answer is negative!

Because some classes in our daily development need to map our corresponding business logic requirements, these classes are not recommended to be handed over to the Spring factory to manage

For example: the entity class pojo and its derivatives

I have talked about so many factories in order to let us understand the underlying design ideas of Spring well, which is conducive to later learning. I believe that after experiencing the above various operations, we should have a certain understanding of the Spring factory. Then, next, Let’s talk about DI

We have explained what DI is, why DI is needed, and related injection problems. So what are we doing now? --coding

First steps:

1.创建类并为其添加set、get方法
2.配置application.xml
3.创建工厂
4.通过工厂获取对象

1. Create a class

2. Configure application.xml

<bean id="student" class="com.xiaozhao.spring.entity.Student">
        <property name="name" value="小赵"/>
        <property name="age" value="24"/>
        <property name="sex" value="男"/>
</bean>

 3 and 4, create factories and get objects

   running result:

From the configuration file, we can see that the name in the <property /> attribute corresponds to the name of each member in our class, and the value corresponds to the value we want to attach to it, so that we can assign values ​​to the attributes in the student object

One question is, what is the injection method we used in the above code? What are the injection methods?

Mentioned in the above steps to add a set method to the class, here is the set method of injection

What are the injection methods:

            1.set

            2. Constructor injection

            3. Reflection injection

Here we first talk about the simplest and most common set injection in our work:

    

Through the above picture, we can see at a glance, the following focuses on several types of writing

Stop talking nonsense and get the code first!


这是被注入对象Student,它的属性基本上涵盖了我们常用的基本类型


package com.xiaozhao.spring.entity;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/15 16:37
 */
public class Student {

    private String name;

    private Integer age;

    private String sex;

    private String[] s;

    private List<String> list;

    private Set<String> set;

    private Map<String,String> map;

    private User user;

    public String[] getS() {
        return s;
    }

    public void setS(String[] s) {
        this.s = s;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", s=" + Arrays.toString(s) +
                ", list=" + list +
                ", set=" + set +
                ", map=" + map +
                ", user=" + user +
                ", properties=" + properties +
                '}';
    }
}
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

这是程序员自定义类型的注入类型

package com.xiaozhao.spring.entity;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/28 23:20
 */
public class User {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The next step is to configure xml

<bean id="student" class="com.xiaozhao.spring.entity.Student">

        <property name="name" value="小赵"/>
        <property name="age" value="24"/>
        <property name="sex" value="男"/>

        <property name="s">
            <list>
                <value>ceshi</value>
                <value>xiaoxiao</value>
            </list>
        </property>

        <property name="list">
            <list>
                <value>cheche</value>
                <value>huaihaui</value>
            </list>
        </property>

        <property name="set">
            <set>
                <value>xiaoming</value>
                <value>xiaojiu</value>
            </set>
        </property>

        <property name="map">
            <map>
                <entry key="ceshi" value="youyou"/>
            </map>
        </property>

        <property name="user" ref="user"/>

        <property name="properties">
            <props>
                <prop key="nihao">enen</prop>
                <prop key="haha">hehe</prop>
            </props>
        </property>

    </bean>
    <bean id="user" class="com.xiaozhao.spring.entity.User">
        <property name="name" value="小花"/>
        <property name="id" value="20"/>
    </bean>

The next step is to get the student

D:\Environment\Java\jdk1.8.0_251\bin\java.exe "...

student = Student{name='小赵', age=24, sex='男', s=[ceshi, xiaoxiao], list=[cheche, huaihaui], set=[xiaoming, xiaojiu], map={ceshi=youyou}, user=com.xiaozhao.spring.entity.User@5abca1e0}, properties={nihao=enen, haha=hehe}}

Process finished with exit code 0

These basic operations should be no problem, then proceed to constructor injection

在这里我将就以上的User来改造

package com.xiaozhao.spring.entity;

/**
 * @author : Carson-Zhao
 * @date : 2020/8/28 23:20
 */
public class User {

    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————
配置文件xml中
    <bean name="user" class="com.xiaozhao.spring.entity.User">
        <constructor-arg value="15"/>
        <constructor-arg value="nihao"/>
    </bean>
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————
运行结果:
D:\Environment\Java\jdk1.8.0_251\bin\java.exe "...

user = User{id=15, name='nihao'}

student = Student{name='小赵', age=24, sex='男', s=[ceshi, xiaoxiao], list=[cheche, huaihaui], set=[xiaoming, xiaojiu], map={ceshi=youyou}, user=User{id=15, name='nihao'}, properties={nihao=enen, haha=hehe}}

Process finished with exit code 0

Points to note:

When the constructor is injected:

Distinguish the number of parameters by controlling the number of <constructor-arg>-tags
 
Distinguish the parameter types by introducing the type attribute in the tag————<constructor-arg type="">
 
problem:
In the future actual combat, application set injection or construction injection?
 
Obviously set injection
 
the reason:
 
1. Construction is troublesome (heavy load)
2. The bottom layer of the Spring framework uses set annotations
 
 
to sum up:
 
 
 Well, about the foundation of Spring IOC and DI, that's almost it. There is a part of the Spring bean creation process. Now I just talked about it. The later BeanPostProcessor did not go into it. This has to wait until the AOP part, which will be slow. Chat slowly, friends you like can discuss together
 
Make complaints:
 
This article is too difficult. From 8.9 to 8.28, it’s also because I get off work too late every day. I get home around ten o’clock. I learn to clock in for an hour. Basically, I have half an hour to write. Life in 996 is also uncomfortable. The day was handed over to girlfriend again, and after doing so, it took a long time to finish writing.
 
plan:
 
In the next article about AOP, I read the relevant knowledge points, and there are still quite a few. It is estimated that it will be a long late-night writing process, but no matter how difficult it is, persistence is victory!
 
 
Finally, if there are like-minded friends who can send a private message, plan and check in together (check in somewhere for 10n+ days after work), Xiao Zhao has nothing here, it's ruthless!
 

Guess you like

Origin blog.csdn.net/weixin_43562937/article/details/107901731