Introduction to spring framework for java learning

Introduction to spring framework for java learning

0x00 Preface

Recently, I have been studying the three frameworks of SSM. In the last article, I have 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 described 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 JavaBeans to do things that previously could only be done by EJBs. 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 the MySQL method 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 code is not efficient, and it is difficult to change if there are too many codes later. Moreover, if it is written in this way, the control is all in the hands of developers, not in the hands of users. What functions should be realized? The control should be in the hands of users, not developers.

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");  //传入xml文件
        userdao MysqLdaoimpl = (userdao)cl.getBean("MysqLdaoimpl");  //获取MysqLdaoimpl方法
        MysqLdaoimpl.select();//调用MysqLdaoimpl方法
    }
}

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

Bean tag details:

作用:

用于配置对象让 spring 来创建的。

默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。

属性:
id: 给对象在容器中提供一个唯一标识。用于获取对象。

class: 指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。

*scope: 指定对象的作用范围。
* singleton :默认值,单例的.
* prototype :多例的.
* request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
* session :WEB 项目中,将对象存入到 session 域中.
* global session :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么
*globalSession 相当于 session.
*init-method: 指定类中的初始化方法名称。
*destroy-method: 指定类中销毁方法名称。

0x04 dependency injection

Bean objects are created from containers. All properties in bean objects are injected into 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. In 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");  //传入xml文件
        Perpon person = (Perpon) cl.getBean("person");
        System.out.println(person);
    }
}

matters needing attention:

Then we can see the execution results.

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:指定参数在构造函数参数列表的索引位置

type:指定参数在构造函数中的数据类型

name:指定参数在构造函数中的名称 

value:它能赋的值是基本数据类型和 String 类型

ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 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:找的是类中 set 方法后面的部分
ref:给属性赋值是其他 bean 类型的
value:给属性赋值是基本数据类型和 string 类型的
实际开发中,此种方式用的较多。

0x05 end

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.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>