Java spring series configuration file operation + bean life cycle + injection of different data types + detailed explanation of injection principle + usage of different label bodies in configuration files

Time:2020-9-24

Operation of configuration file of spring series

Write at the front of the article
This article takes you to master the basic operation of spring configuration file and lead you to clarify the concept of dependency injection. This article covers a wide range of contents. If you have read it patiently, you should improve yourself
在这里插入图片描述

The role of spring configuration file

Spring configuration file is a drawing used by spring factory for bean production, dependency injection and bean instance distribution. It is similar to human brain. We must master the usage method of this drawing before we can carry out relevant operation and flexibly use this drawing to accurately express our intention. Strategize and win thousands of miles. Spring’s configuration file is one or more standard XML documents, applicationContext.xml File is the default configuration file. When the container startup cannot find the configuration file, it will try to load the configuration file.
Development steps of the program without using spring

Here, for example, to configure a user class, userimp as the interface and user as the implementation class, we used a userimp interface to receive the implementation object of a user, which was originally through the following code:

UserImp user=new User()

flow chart

在这里插入图片描述

The disadvantage of using the above method is that the code coupling is too high

Using spring framework operation

Here, taking the configuration of a user class as an example, userimp is the interface and user is the implementation class. We use a userimp interface to accept a user implementation object. The code is as follows:

Userdao user = spring client. GetBean (ID identifier)

So what is the internal principle? In order to realize decoupling, the configuration document is basically used. Spring is no exception. Let’s take a flow diagram to show you a better understanding

Flow chart

在这里插入图片描述

How to get started with spring

1. In pom.xml Import spring coordinates in the framework
2. Create bean
3. Create applicationContext.xml
4. Configure in XML
5. Create the ApplicationContext object getBean

Implement a simple spring case

Project structure
在这里插入图片描述

Main function, get bean instance with spring API
Existing folder:
在这里插入图片描述

package com.pjh.Dao.Demo;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new                                                   ClassPathXmlApplicationContext("applicationContext.xml");
        UserDaoImp userDaoImp =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        userDaoImp.save();
    }
}

Create spring’s profile:applicationContext.xml
Existing folder:
在这里插入图片描述
code

Import the basic coordinates of spring development, and pom.xml configuration file
file location
在这里插入图片描述
code

4.0.0

com.pjh
SpringIOCInit
1.0-SNAPSHOT

org.springframework
spring-context
5.0.3.RELEASE

Write information about the userdaoimp class:

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
public class UserDaoImp  implements  UserDao{
    public void save() {
        System.out.println("save runing!!");
    }
}

Operation results
Successful execution
在这里插入图片描述

Bean tag introduction and basic properties

3.1 basic configuration of bean tag
Used to submit the configuration file to spring configuration. The default call is to construct without parameter. If there is no non parameter construction, the creation fails
ID: unique identifier of bean instance in spring
Class: fully qualified name of bean instance

If you copy the parameterized construction in an implementation class, remember to add a nonparametric constructor, because the original nonparametric construction will be eliminated after you copy the parametric construction. If you still use the nonparametric construction in the spring configuration file by default at this time, an error will be reported

As shown in the figure
在这里插入图片描述
3.2 label range configuration of bean

在这里插入图片描述

Here’s a look at singleton and prototype
When the scope value is singleton
Instantiation number of bean: 1
Bean instantiation time: when spring core configuration file is loaded
Bean life cycle:
Object creation: object creation when the application is loaded
Object running: the object is alive as long as the container is present
Object destruction: when the application is unloaded and the container is destroyed
Example
Profile information

Main function code, using spring API to create two bean objects

package com.pjh.Dao.Demo;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Gets the first bean object
        UserDaoImp userDaoImp =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Get the second bean object
        UserDaoImp userDaoImp2 =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Output the memory address of the first bean object
        System.out.println(userDaoImp);
        //Output the memory address of the second bean object
        System.out.println(userDaoImp2);
    }
}

Operation results
The address values of the two objects are the same, indicating that they are the same object
在这里插入图片描述

When scope value is prototype:
Instantiation format of bean: multiple
Instantiation time of bean: instantiate bean when calling getbean() method
Object creation: creates a new object instance when using an object
Object running: objects exist as long as they are in use
Object destruction: if an object is not used for a long time, it will be recycled by Java’s garbage collection mechanism

Examples
Profile information

Main function code, using spring API to create two bean objects

package com.pjh.Dao.Demo;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Get first bean object
        UserDaoImp userDaoImp =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Get the second bean object
        UserDaoImp userDaoImp2 =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Output the memory address of the first bean object
        System.out.println(userDaoImp);
        //Output the memory address of the second bean object
        System.out.println(userDaoImp2);
    }
}

Operation results
The address values of the two objects are different, indicating that they are not objects

在这里插入图片描述

3.3bean lifecycle configuration
Init method: Specifies the initialization method in the class
Destroy method: Specifies the destruction method in the class
Using these two methods, we can prove the creation time of the bea object mentioned above

Write the spring core configuration file information
Scope: prototype (two cases)

Write the relevant profile information for userdaoimp

package com.pjh.Dao.Demo;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Gets the first bean object
        UserDaoImp userDaoImp =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Get the second bean object
        UserDaoImp userDaoImp2 =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Output the memory address of the first bean object
        System.out.println (object 1);
        System.out.println(userDaoImp);
        //Output the memory address of the second bean object
        System.out.println ("object 2");
        System.out.println(userDaoImp2);
    }
}

Operation results
The constructor is called twice, indicating that two objects have been created
The order in which methods are called: constructor method > initialization method
在这里插入图片描述
Scope: prototype (single case)
Profile code

Principal function

package com.pjh.Dao.Demo;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Gets the first bean object
        UserDaoImp userDaoImp =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Get the second bean object
        UserDaoImp userDaoImp2 =(UserDaoImp) classPathXmlApplicationContext.getBean("userDaoImp");
        //Output the memory address of the first bean object
        System.out.println (object 1);
        System.out.println(userDaoImp);
        //Output the memory address of the second bean object
        System.out.println ("object 2");
        System.out.println(userDaoImp2);
    }
}

Operation results

The constructor and initializer are called only once, so they are the same object

在这里插入图片描述
**

Three ways of bean instantiation

**
1. Use nonparametric construction to instantiate
It will create an instantiated object according to the default nonparametric construction. If there is no method without parameter construction, an error will be reported here. We have already made it very clear

2. Factory static method instantiation
Factory static method returns instantiated objects

package com.pjh.Dao.factory;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
public class factory {
    public static UserDaoImp getUserDaoImp(){
        return new UserDaoImp();
    }
}

3. Factory instance method instance instantiation
The factory’s non static method is put back into the bean instance

package com.pjh.Dao.factory;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
public class factory {
    public UserDaoImp getUserDaoImp(){
        return new UserDaoImp();
    }
}

Code for configuration file

Dependency injection

Dependency injection is the core of spring frameworkIOCThe essence of the implementation is to transfer the operation of creating objects to spring through the inversion of control. However, it is impossible to have no dependency in the code,IOC decoupling only reduces the coupling between them and does not eliminate the dependency completelyFor example, the business layer still calls the methods of the persistence layer, but the dependency relationship between the business layer and the persistence layer is left to spring to manage after using spring,Simply put, let the framework complete the operation of the persistence layer passing into the business layer.

The following describes the operation of dependency injection by using the userdaoimp class inside the userservice class
Userdaoimp code

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
public class UserDaoImp  implements  UserDao{
    public void save() {
        System.out.println("save runing!!");
    }
}

Userservice code

package com.pjh.Dao.service;
import com.pjh.Dao.UserDao;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class userService {
    public  void save(){
        ClassPathXmlApplicationContext userDao = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao1 = (UserDaoImp)userDao.getBean("userDao");
        userDao1.save()
    }
}

Configuration files for spring
Leave the creation of userservice and userdao to spring

Main function code
Get the userservice from the container for operation

package com.pjh.Dao.Demo;
import com.pjh.Dao.UserDaoImp.UserDaoImp;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo3 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Get the second bean object
        UserDaoImp userDaoImp =(UserDaoImp) classPathXmlApplicationContext.getBean("userService");
        //Call the save method
        userDaoImp.save();
    }
}

Analysis of dependency injection in the above cases
The current practice is to get userimp and userdao outside the container to combine them in the program
加粗样式

The ultimate goal
Since both userservice and userdao are inside the sprint container, you can set the userdao inside the userservice in the spring container
在这里插入图片描述

So what should we do to set the userdao into the userservice in the configuration file? This is nothing more than the use of 1. Set method 2. Constructor, we will explain one by one

**

1. Set method injection

**

Add setuserda method to userservice

package com.pjh.Dao.service;
import com.pjh.Dao.UserDao;
public class UserService {
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public  void save(){
        userDao.save();
    }
}

Calling set method in Spring container is injected by row.
How to configure configuration file 1

**

Configuration profile side 2
Using the P namespace is also set injection in essence, but it is simpler than the above method, which is reflected in the configuration file
First, we’ll introduce the P namespace

xmlns:p="http://www.springframework.org/schema/p"

Second, we need to modify the injection method

Entire configuration file

Although name and ref are of the same name, name refers to userdao, which is a parameter in userservice. There is a parameter named userdao of type userdao in userservice, and ref is a bean named userdao in the current XML file, which is used to pass into userservice

2. Injection with construction method

Method 1
Create a parametric construct

package com.pjh.Dao.service;
import com.pjh.Dao.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserService {
    public  void save(){
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //Get the second bean object
        UserDao userService=(UserDao) classPathXmlApplicationContext.getBean("userDao");
        //Call the save method
        userService.save();
    }
}

Method 2

Configure spring container call to be injected by row when constructively constructed

The first step is to set the parameter structure in the userservice

package com.pjh.Dao.service;
import com.pjh.Dao.UserDao;
public class UserService {
    private UserDao userDao;
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }
    public  void save(){
        //Call the save method
        userDao.save();
    }
}

Second, change the code in the spring configuration file

Although name and ref are of the same name, name refers to userdao, which is a parameter in userservice. There is a parameter named userdao of type userdao in userservice, and ref is a bean named userdao in the current XML file, which is used to pass into userservice

**

Injection of common data types and sets

**

The above data types are all injected reference beans. In addition to reference data types, collections, ordinary data types, etc., they can be injected
Three types of data injected
Common data type
Reference data type
Collection data type

Reference data types, which we have described above, let’s talk about the injection of common data types and sets

Common data types and collections
1. Common data type injection
Example: injecting age and name into the userdaoimp class

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
public class UserDaoImp  implements  UserDao{
    private  int age;
    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void save() {
        System.out.println(name+":"+age);
    }
}

Code in the spring configuration file

2. Set data type listinjection

Example: injecting intlist into the userdaoimp class

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
import java.util.List;
public class UserDaoImp  implements  UserDao{
    private List intlist;
    public void setIntlist(List intlist) {
        this.intlist = intlist;
    }
    public void save() {
        System.out.println(intlist);
    }
}

Configuration file code of spring

1
              2
              3

3. List injection of set data type
The reference data type here is replaced by a simple user class. The user class code is as follows

package com.pjh.Dao.UserDaoImp;
public class User {
    private  int age;
    private  String name;

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

Code in userdaoimp

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
import java.util.List;
public class UserDaoImp  implements  UserDao{
    private List userslist;
    public void setUserslist(List userslist) {
        this.userslist = userslist;
    }
    public void save() {
        System.out.println(userslist);
    }
}

Code in spring core configuration file

4. Set data type mapInjection of

The reference data type here is replaced by a simple user class. The user class code is as follows

package com.pjh.Dao.UserDaoImp;
public class User {
    private  int age;
    private  String name;

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

Code in userdaoimp

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
import java.util.Map;
public class UserDaoImp  implements  UserDao{
    private Map usersMap;
    public void setUsersMap(Map usersMap) {
        this.usersMap = usersMap;
    }

    public void save() {
        System.out.println(usersMap);
    }
}

Code in spring configuration file

5. Injection of set data type properties

Code in userdaoimp

package com.pjh.Dao.UserDaoImp;
import com.pjh.Dao.UserDao;
import java.util.Map;
import java.util.Properties;

public class UserDaoImp  implements  UserDao{
    private Properties properties;

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void save() {
        System.out.println(properties);
    }
}

Code in spring configuration file

aaa
           bbb

Introduction of other configuration files (module development)

The above is only a small case, so we only use one configuration file. However, if we develop a large project in the future, the configuration file of spring is very complicated and bulky. We can disassemble the configuration file into other configuration files according to the development modules, which is conducive to our management. We can import the configuration file in the main configuration file of spring load

Summary of profile Tags

label
    ID attribute: the unique ID of the bean instance in the container, which cannot be repeated
    Class property: full qualified name of bean to instantiate
    Scope attribute: the scope of bean, usually singleton (default) and prototype
    label:属性注入
        Name attribute: attribute name
        Value attribute: the injected normal attribute value
        Ref attribute: injected object reference value
        label
        label
        label
    label
label:导入其他的Spring的分文件

Inheritance of ApplicationContext

The application context represents the application context

在这里插入图片描述
Implementation class of applicationj

1)ClassPathXmlApplicationContext 
      It is recommended to load the profile from the root path of the class
2)FileSystemXmlApplicationContext 
      It loads the configuration file from the disk path, and the configuration file can be anywhere on the disk.
3)AnnotationConfigApplicationContext
      When using annotations to configure container objects, you need to use this class to create spring containers. It is used to read annotations.

The above is the detailed tutorial of spring configuration file. It has been written for several hours, which is not easy. In the process of liver text, many errors have been encountered, and they are all corrected one by one. The article also tries to present it in the form of pictures and texts, which is conducive to the understanding of readers. It is not easy to do it. If you think it is helpful, please praise and pay attention to it. I will bring you more articles and knowledge points

在这里插入图片描述

Recommended Today

Front end star 2020_ 4_ 11 course notes

Front end Engineering Standardization Git git flow Compilation specification modularization Core demand avoids variable pollution CSS modularization JS modularization Componentization Encapsulation of UI and logic automation Hand over repetitive and time-consuming operations to tools Initializing cli Building webpack Test jest Deploying Jenkins JS animation Animation, the native interface of JS Of course, the various native […]