Introduction to Spring framework for Java learning

Introduction to Spring framework for Java learning

0x00 Preface

Recently, I've been studying the three frameworks of SSM. The previous article has updated the relevant contents of Mybatis. Then this article will write the introduction to Spring.

0x01 Spring overview

Spring is an open source framework. Spring is a lightweight Java development framework rising in 2003. It is derived from some concepts and prototypes elaborated by Rod Johnson in his book expert one on one J2EE development and design.

It is created to solve the complexity of enterprise application development. One of the main advantages of the framework is its layered architecture, which allows users to choose which component to use, and provides an integrated framework for J2EE application development.

Spring uses basic JavaBean s to do things that previously could only be done by EJB s. However, the use 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. The core of spring is inversion of control (IoC) and aspect oriented (AOP).

0x02 meaning of spring usage

First, let's look at a piece of code.

dao interface:

package com.test.dao;
public interface userdao {
    void select();
}

mysqldaoimpl:

package com.test.dao;

public class mysqldaoimpl implements userdao{
    public void select() {
        System.out.println("mysqldaoimpl");
    }
}


mssqldaodimpl:

package com.test.dao;

public class mssqldaoimpl implements userdao {
    public void select() {
        System.out.println("mssqlselect ");
    }
}

test class:

package com.test.domain;

import com.test.dao.mysqldaoimpl;
import com.test.dao.userdao;

public class test1 {
    public static void main(String[] args) {
        userdao mysqldaoimpl = new mysqldaoimpl();
        mysqldaoimpl.select();
    }
}

The specific implementation is not written. Here is just a demonstration of the difference.

Here, an interface is written to represent a query method, and then two implementation classes are written, namely mysql connection and mssql connection query.

We can notice that if we want to call mysql methods in the test class, we directly new an object of the implementation class. If we want to query mssql later, we need to modify the code. This kind of code is not efficient, and it is not easy to change if there are more codes later. The developer's right to realize the function should be in the user's hand, not in the user's hand.

Then you can use the Spring framework to implement it. Although there are other ways to solve this problem, the implementation code is cumbersome, so why don't we use a more simple and convenient method?

0x03 Spring usage

First, configure the coordinates of spring.

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

After configuration, let's configure our xml 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">
    <bean id="mysqldaoimpl" class="com.test.dao.mysqldaoimpl"/>

    <bean id="mssqldaoimpl" class="com.test.dao.mssqldaoimpl"/>


</beans>

test class:

package com.test.domain;


import com.test.dao.userdao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test1 {
    public static void main(String[] args) {
         ApplicationContext cl = new ClassPathXmlApplicationContext("bean.xml");  //Incoming xml file
        userdao mysqldaoimpl = (userdao)cl.getBean("mysqldaoimpl");  //Get mysqldaoimpl method
        mysqldaoimpl.select();//Call mysqldaoimpl method
    }
}

Configure and directly pass in the xml file, and get the method. Then you can directly call the method and use it. There is no need to implement the instantiation object of the class in new.

Bean tag details:

effect:

Used to configure objects spring To create.

By default, it calls the parameterless constructor in the class. If there is no parameterless constructor, it cannot be created successfully.

Properties:
id:  Provide the object with a unique identifier in the container. Used to get objects.

class:  Specifies the fully qualified class name of the class. Used to create reflective objects. The parameterless constructor is called by default.

*scope:  Specifies the scope of the object.
* singleton :Default, singleton.
* prototype :Multiple cases.
* request :WEB In the project,Spring Create a Bean Object of,Save objects to request In domain.
* session :WEB In the project,Spring Create a Bean Object of,Save objects to session In domain.
* global session :WEB In the project,Applied in Portlet environment.without Portlet Environment so
*globalSession amount to session.
*init-method:  Specifies the name of the initialization method in the class.
*destroy-method:  Specifies the name of the destruction method in the class.

0X04 dependency injection

The creation of bean objects comes from containers. All properties in bean objects are injected by containers. Let's take a look at several common injection methods

Structural injection

Construction injection: as the name suggests, it is to use the constructor in the class to assign values to member variables. Note that the assignment operation is not done by ourselves, but through configuration
Let the spring framework inject for us.

First define an entity class:

package com.test.doamin;


import java.util.Date;

public class Perpon {
    private String name;
    private Integer age;

    public Perpon() {
    }

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

    public Perpon(String name, Integer age, Date date) {
        this.name = name;
        this.age = age;
        this.date = date;
    }

    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 Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    private Date date;

}

In normal times, we usually directly assign values to new, or use the set method to assign values to it. Under the spring framework, we only need to configure the xml file to inject constructors into it.

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

    <bean id="person" class="com.test.doamin.Perpon">

    <constructor-arg name="name" value="xiaoming"/>
        <constructor-arg name="age" value="18"/>
        <constructor-arg name="date" ref="now"/>


    </bean>
    <bean id = "now" class="java.util.Date"/>


</beans>

test class:

    public static void main(String[] args) {
         ApplicationContext cl = new ClassPathXmlApplicationContext("bean.xml");  //Incoming xml file
        Perpon person = (Perpon) cl.getBean("person");
        System.out.println(person);
    }
}

matters needing attention:

Class needs to provide a constructor corresponding to the parameter list.

Then we can see the execution results.

Perpon{name='xiaoming', age=18, date=Sun Aug 30 05:32:35 CST 2020}

Print out the person. Here we see that these member variables have been assigned, which is completed by our framework.

Constructor Arg tag attribute:

index:Specifies the index position of the parameter in the constructor parameter list

type:Specifies the data type of the parameter in the constructor

name:Specifies the name of the parameter in the constructor 

value:The values it can assign are basic data types and String type

ref:It can assign other values bean Type, that is, it must be configured in the configuration file bean

Set injection

 <bean id="person" class="com.test.doamin.Perpon">
        
    <property name="name" value="xiaoming"/>
    <property name="age" value="18"/>
    <property name="date" ref="now"/>
        

    </bean>
    <bean id = "now" class="java.util.Date"/>

property tag properties:

name: Found in class set The latter part of the method
ref: Assigning a value to an attribute is something else bean Type
value: Assigning a value to an attribute is the basic data type and string Type
 In actual development, this method is used more.

End of 0x05

In fact, I was confused when I saw this thing in front. Later, I found that it was quite simple. Most of them were conceptual things, which were difficult to understand, but the use of general frameworks was relatively simple.

Tags: Java

Posted by frist44 on Thu, 19 May 2022 12:00:53 +0300