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


Please add image description

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 difficulty and development of Java enterprise-level applications. 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.

1. Introduction to Spring

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

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 to the business layer to the presentation layer. This is why it is called Spring. It’s a one-stop framework.

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, email 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:

Transaction module: This module is used for Spring management transactions. As long as Spring manages objects, they can get the benefits of Spring management transactions. There is no need to control transactions in code, and it supports programming and declarative transaction management.
JDBC module: Provides a JBDC sample template. Using these templates can eliminate the traditional lengthy JDBC coding and necessary transaction control, and you can enjoy the benefits of Spring's transaction management.
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.
OXM module: Provides an Object/XML mapping implementation, mapping Java objects into XML data, or mapping XML data into Java objects. Object/XML mapping implementations include JAXB, Castor, XMLBeans and XStream.
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 sending between two applications or in a distributed system. Messages 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 methods, and supports testing frameworks such as JUnit and TestNG.

3. First introduction to Ioc and DI

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, if we need to use a method of an object, we need to create the object first through new. At this time, we are taking the initiative; with IoC, we hand over the control of creating the object to the IoC container. At this time, the container Helps create and inject dependent objects. Our program passively accepts objects created by the IoC container and inverts control, so it is called inversion of control.

Since IoC is indeed not straightforward enough, the concept of DI (Dependency Injection) was proposed, which allows a third party to 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 only need to let Spring help us create it, which is called inversion of control; then Spring will help us set the required objects into our class, which 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");

使用属性注入

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, and the calling class provides corresponding injection methods by implementing the 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 containers. 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. That’s it. 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 packages in the core module, beans, core, context, expression, etc. 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"> 

    //配置要创建的类  
    <bean id="user" class="com.cad.domain.User"/>        
</beans>

(4) Conduct testing

//This is just code for testing, we will not write it like this later
public class Test {

@org.junit.Test
public void test(){
    
    
    //加载配置文件
    ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
    //获取对象
    User user=(User) context.getBean("user");
    System.out.println(user);
    //调用方法
    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'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();
    }
}

// 配置文件
<bean id="userdao" class="com.cad.domain.UserDao"></bean> 
//这样在实例化service的时候,同时装配了dao对象,实现了依赖注入
<bean id="userservice" class="com.cad.domain.UserService">
    //ref为dao的id值
    <property name="userdao" ref="userdao"></property>
</bean>

4. Spring resource access artifact - Resource interface

The classes provided by JDK for accessing resources (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 in Spring Playing an indispensable role in the 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: Resource under the class path, the resource is expressed relative to the class path
FileSystemResource: File system resource, the resource is expressed in the file system path, such as d:/a/b.txt
InputStreamResource: Corresponds An InputStream's resource
ServletContextResource: A class designed for accessing resources in a container context. Responsible for loading resources UrlResource with a path relative to the web application root directory
: 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.
————————————————

Guess you like

Origin blog.csdn.net/2202_75623950/article/details/132832387