[Spring] Development framework Spring core technology including Resource interface is explained in detail

Insert image description here

Preface

Spring is a lightweight open source framework in the field of Java EE programming. It was proposed and founded in 2002 by Rod Johnson, known as the “Father of Spring”. Its goal is to simplify the development of Java enterprise applications. Development difficulty and cycle.
Spring has been favored since its birth and has always been the first choice for Java enterprise application development by the majority of developers. Today, Spring has become synonymous with Java EE and the de facto standard for building Java EE applications.


📕About the author: Hengchuan who loves running is a blogger who is committed to C/C++, Java, Python and other programming languages, loves running, and loves music.
📗This article is included in Hengchuan’s daily report series. If you are interested, you can take a look.
📘Related columns C language elementary, C language advanced series, etc. If you are interested, you can take a look
📙The Python zero-based introductory series and the Java introductory series are under development. Friends who like Python and Java can pay attention!

Spring core technology

  • 1. Spring Introduction
  • 2. Spring architecture
    • 2.1 Core Module (Core Container)
  • 2.2 AOP module
  • 2.3 Data Access/Integration module
  • 2.4 Web module
  • 2.5 Test module
  • 3. First introduction to Ioc and DI
    • 3.1 IoC Inversion of Control and DI Dependency Injection
  • 3.2 Several common injection methods
  • 3.3 Spring’s IoC example
  • 3.4 Spring’s DI example
  • 4. Spring resource access artifact – Resource interface
    • 4.1 Main methods of Resource interface
  • 4.2 Specific implementation class of Resource interface
  • 4.3 Spring’s resource loading mechanism
  • 5. Hengchuan Book Donation Activity

1. Spring Introduction

Spring is a one-stop lightweight open source framework for layered Java SE/EE applications. The core of Spring is IOC and AOP.
The main advantages of Spring include:

  • It facilitates decoupling and simplifies development. Through the IoC container provided by Spring, we can control the dependencies between objects by Spring to avoid high program coupling caused by hard coding.
  • AOP programming support, through the AOP function provided by Spring, facilitates aspect-oriented programming.
  • Declarative transaction support, in Spring, we can be freed from monotonous and boring transaction management code, flexibly manage transactions through declarative methods, and improve development efficiency and quality.
  • Convenient for program testing, almost all testing work can be performed using non-container-dependent programming methods.
  • It is convenient to integrate various excellent frameworks, and Spring provides direct support for various excellent frameworks.

2. Spring architecture

As shown in the figure below, the entire spring framework can be divided into five main modules according to their functions. These five modules provide almost everything needed for enterprise applications, from the persistence layer, business layer to presentation layer. Support, this is why Spring is called a one-stop framework.
Insert image description here

2.1 Core Module (Core Container)

Spring's core module implements the IoC function, which separates the dependencies between classes from the code and uses configuration to describe dependencies. The IoC container is responsible for the creation, management, acquisition, etc. of classes. The BeanFactory interface is the core interface of the Spring framework and implements many core functions of the container.

The Context module is built on the core module and extends the functions of BeanFactory, including internationalization, resource loading, mail service, task scheduling and many other functions. ApplicationContext is the core interface of the Context module.

Expression Language is an extension of Unified Expression Language (EL), which supports setting and getting object properties, calling object methods, operating arrays, collections, etc. It can be used to easily interact with the Spring IoC container through expressions.

2.2 AOP module

The Spring AOP module provides an implementation that meets the AOP Alliance specification and also integrates the AOP language-level framework AspectJ. Coupling can be reduced through AOP.

2.3 Data Access/Integration module

This module includes JDBC, ORM, OXM, JMS and transaction management:

  1. Transaction module: `This module is used to manage transactions with Spring. As long as it is a Spring-managed object, it can get the benefits of Spring-managed transactions. There is no need to control transactions in the code, and it supports programming and declarative transaction management.
  2. JDBC module: Provides a JBDC sample template. Using these templates can eliminate traditional lengthy JDBC coding and necessary transaction control, and you can enjoy the benefits of Spring's transaction management.
  3. ORM module: Provides seamless integration with popular “object-relational” mapping frameworks, including hibernate, JPA, MyBatis, etc. And you can use Spring transaction management without additional transaction control.
  4. OXM module: Provides an implementation of Object/XML mapping, mapping Java objects into XML data, or mapping XML data into java objects. Object/XML mapping implementations include JAXB, Castor, XMLBeans and XStream.
  5. JMS module: used for JMS (Java Messaging Service), providing a set of “message producer, message consumer” templates for simpler use of JMS. JMS is used for distribution between two applications. Send messages in a conventional system for asynchronous communication.

2.4 Web module

This module is built on the ApplicationContext module and provides Web application functions, such as file upload, FreeMarker, etc. Spring can integrate MVC frameworks such as Struts2. In addition, Spring itself provides the MVC framework Spring MVC.

2.5 Test module

Spring can perform almost all testing work using non-container-dependent programming and supports testing frameworks such as JUnit and TestNG.

3. First introduction to Ioc and DI

Insert image description here

Let's first explain the concept of IoC. IoC (Inverse of Control) is the core of the Spring container, but the concept of IoC is relatively obscure and difficult to understand.

3.1 IoC Inversion of Control and DI Dependency Injection

In traditional programming, when we need to use the method of an object, we need to create an object through new first, and we are taking the initiative at this time; with IoC, we hand over the control of creating objects to the IoC container. At this time, the container helps create and inject dependent objects. Our program passively accepts the objects created by the IoC container, and the control is reversed, so it is called inversion of control.

Since IoC is indeed not straightforward enough, the concept of DI (Dependency Injection) was proposed, which is to let a third party implement injection to remove the dependency between our classes and the classes that need to be used. In general, IoC is the purpose, DI is the means, and the process of creating objects often means dependency injection. In order to implement IoC, we reverse the way of generating objects from the traditional way (new). When we need to create related objects, the IoC container helps us inject them (DI).

To put it simply, if we need another class in our class, we just need to ask Spring to create it for us. This is called inversion of control; and then Spring will help us set the required objects into our class. This is called dependency injection.

3.2 Several common injection methods

Injection using parametric constructor

public class  User{
    private String name;
    public User(String name){
        this.name=name;
    }
} 

    User user=new User("tom"); 

Use attribute injection

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

     User user=new User();
     user.setName("jack"); 

Use interface injection

// Extract all dependency injection methods of the calling class into the interface,The calling class provides the corresponding injection method by implementing this interface。 

public interface Dao{
    public void delete(String name);
} 

public class DapIml implements Dao{
    private String name;
    public void delete(String name){
        this.name=name;
    }
} 

Complete dependency injection through the container
The above injection methods require us to inject manually. If there is a third-party container that can help us complete the instantiation of classes and the assembly of dependencies, then we only need to focus on the development of business logic. `Spring is such a container. It describes classes and dependencies between classes through configuration files or annotations, and automatically completes class initialization and dependency injection.

3.3 Spring’s IoC example

(1) Create a project and import the jar package

Here we are only doing IoC operations, so we only need to import the jar package, beans, core, context, expression, etc. in the core module. Because there is no log-related jar package in spring, we also need to import log4j and commons-logging.
(2) Create a class

public class User {
    public void add(){
        System.out.println("add.....");
    }
} 

(3) Create an xml configuration 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"> 

    //Configure the class to be created 
    <bean id="user" class="com.cad.domain.User"/>        
</beans> 

(4) Conduct testing

//This is just code for testing,I won’t write like this later
public class Test {

    @org.junit.Test
    public void test(){
        //Load configuration file
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        //Get object
        User user=(User) context.getBean("user");
        System.out.println(user);
        //call method
        user.add();
    }
} 

When the container starts, Spring will automatically instantiate the bean and complete the assembly of dependencies based on the description information of the configuration file. The bean instance can be obtained from the container and can be used directly. Why can Spring magically instantiate and configure the beans used by the program with just a simple configuration file? The answer is through Java&#39;s reflection technology.

3.4 Spring’s DI example

Our service layer always uses the dao layer. In the past, we always created new dao objects in the service layer. Now we use dependency injection to inject the dao layer into the service layer.

// UserDao
public class UserDao {
    public void add(){
        System.out.println("dao.....");
    }
}

// UserService
public class UserService {
    UserDao userdao;
    public void setUserdao(UserDao userdao){
        this.userdao=userdao;
    }

    public void add(){
        System.out.println("service.......");
        userdao.add();
    }
}

----------------------------------------------------

// Configuration file
<bean id="userdao" class="com.cad.domain.UserDao"></bean> 
//This is instantiatingservicewhen,Assembled at the same timedaoobject,Implemented dependency injection
<bean id="userservice" class="com.cad.domain.UserService">
    //reffordaoofidvalue
    <property name="userdao" ref="userdao"></property>
</bean> 

4. Spring resource access artifact – Resource interface

The classes for accessing resources provided by JDK (such as java.NET.URL, File) are not very convenient to meet the access needs of various underlying resources. Spring designed a Resource interface to provide applications with a stronger ability to access underlying resources. This interface has implementation classes corresponding to different resource types.

4.1 Main methods of Resource interface

  • boolean exists(): whether the resource exists
  • boolean isOpen(): whether the resource is open
  • URL getURL(): Returns the URL of the corresponding resource
  • File getFile(): Returns the corresponding file object
  • InputStream getInputStream(): Returns the input stream of the corresponding resource

Resource plays an indispensable role in the Spring framework. The Spring framework uses Resource to load various resources, including configuration file resources, international attribute resources, etc.

4.2 Specific implementation class of Resource interface

  • ByteArrayResource: Resource represented by binary array
  • ClassPathResource: Resources under the class path, resources are expressed relative to the class path
  • FileSystemResource: File system resource, the resource is represented by a file system path, such as d:/a/b.txt
  • InputStreamResource: Resource corresponding to an InputStream
  • ServletContextResource: Class designed for accessing resources in a container context. Responsible for loading resources with a path relative to the web application root directory
  • UrlResource: encapsulates java.net.URL. Users can access any resource that can be represented by URL, such as Http resources, Ftp resources, etc.

4.3 Spring’s resource loading mechanism

In order to access different types of resources, the corresponding Resource implementation class must be used, which is more troublesome. Spring provides a powerful mechanism for loading resources. The corresponding resources can be loaded only through the special identification of the resource address.
Spring defines a set of resource loading interfaces. The ResourceLoader interface has only one getResource(String location) method, which can load file resources based on the resource address. Resource addresses only support addresses with resource type prefixes and do not support Ant-style resource path expressions. ResourcePatternResolver extends the ResourceLoader interface and defines a new interface method getResources(String locationPattern), which supports expressions with resource type prefixes and Ant-style resource paths. PathMatchingResourcePatternResolver is a standard implementation class provided by Spring.