[Spring from entry to actual combat tutorial] Chapter 1 Overview of Spring

1. Overview of Spring

1.1 What is Spring

    Spring is a currently mainstream Java EE lightweight open source framework and one of the most successful frameworks in the Java world. Spring was proposed and founded by "Father of Spring" Rod Johnson. Its purpose is to simplify the development difficulty and development cycle of Java enterprise applications.
    
    Since the official release of Spring 1.0 in April 2004, Spring has entered the fifth major version, which is what we often call Spring 5.
    
    Spring has been favored since its inception, and has been regarded as the first choice by developers for Java enterprise application development. Today, Spring has become synonymous with Java EE and the de facto standard for building Java EE applications.
    
    The Spring Framework is not limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling. The Spring framework is also a super glue platform, in addition to providing its own functions, it also provides the ability to glue other technologies and frameworks.
    
    Spring is a lightweight Inversion of Control (IOC) and Aspect Oriented (AOP) container framework.

Specifically describe Spring:

    Lightweight: Spring is lightweight in terms of both size and overhead. The complete Spring framework can be distributed in a JAR file that is just over 1MB in size. And the processing overhead required by Spring is negligible. Furthermore, Spring is non-intrusive: typically, objects in a Spring application do not depend on Spring-specific classes. The Servlet we learned before is intrusive, because a Java class must implement or inherit the Servlet API if it wants to become a Servlet, but Spring basically does not.
    
    Core idea:
        Inversion of control: IOC (inversion of control).
        Dependency injection: DI (dependency injection).
        Aspect-oriented programming: AOP (aspect oriented programming).
    
    Container: Spring contains and manages the configuration and life cycle of application objects, in the sense that it is a container, you can configure how each of your beans is created - based on a configurable prototype (prototype), your bean can Create a separate instance or spawn a new one every time you need it - and how they relate to each other.
    
    Framework: Spring can configure and combine simple components into complex applications. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides many basic functions (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.
    
    One-stop shop: On the basis of IOC and AOP, it can integrate open source frameworks of various enterprise applications and excellent third-party class libraries (for example: collaborative work between Struts2 and Hibernate frameworks), Spring is a bridge or management in the program Or, the entire application relies on Spring to run. In fact, Spring itself also provides SpringMVC for the presentation layer and SpringJDBC for the persistence layer.

1.1.1 The birth and development of Spring

    The early J2EE (Java EE platform) advocated the development method with EJB as the core, but this development method has various disadvantages in the actual development process, such as complex use, bloated code, strong intrusive code, long development cycle, and difficult porting Big wait.

    In his best-selling book "Expert One-on-One J2EE Design and Development" edited in 2002, Rod Johnson analyzed and negated the various bloated structures of EJB one by one, and replaced them in a more concise way.

    In this book, Rod Johnson shows, through a 30,000-line appendix, how to build a high-quality, scalable Java application without using EJBs. In this appendix, Rod Johnson has written tens of thousands of lines of infrastructure code, including many reusable Java interfaces and classes such as ApplicationContext, BeanFactory, and more. The root package for these classes is named com.interface21, which means: This is a reference for the 21st century.

    This book had a far-reaching impact. Later, Rod Johnson open sourced the code of com.interface21, and named this new framework "Spring", which means: Spring is like a ray of spring breeze, sweeping away the cold winter of traditional J2EE.

    In February 2003, Spring version 0.9 was released, which adopted the Apache 2.0 open source protocol; in April 2004, Spring version 1.0 was officially released. So far, Spring has entered the fifth major version, which is what we often call Spring 5.

1.1.2 Narrow and broad sense of Spring

    In different contexts, Spring represents different meanings. Next, we will introduce Spring from the perspectives of "broad sense" and "narrow sense".
    
    Official website: https://spring.io/

Spring in a broad sense: Spring technology stack

    Spring in a broad sense refers to the Spring technology stack with Spring Framework as the core.

    After more than ten years of development, Spring is no longer a pure application framework, but has gradually developed into a mature technology composed of multiple different sub-projects (modules), such as Spring Framework, Spring MVC, SpringBoot, Spring Cloud, Spring Data, Spring Security, etc., among which Spring Framework is the basis of other sub-projects.

    These sub-projects cover everything from enterprise-level application development to cloud computing, and can help developers solve various practical problems that arise in the process of software development, bringing developers a better development experience.

project name describe
Spring Data The data access module provided by Spring provides good support for JDBC and ORM. Through it, developers can use a relatively uniform way to access data located in different types of databases.
Spring Batch A lightweight framework for daily batch processing tasks in enterprise-level systems, which can help developers easily develop robust and efficient batch processing applications.
Spring Security Formerly known as Acegi, it is one of the more mature submodules in Spring. It is a customizable authentication and access control framework.
Spring Mobile It is an extension of Spring MVC to simplify the development of mobile web applications.
Spring Boot It is a new framework provided by the Spring team. It provides some out-of-the-box configurations for Spring and third-party libraries, which can simplify the construction and development process of Spring applications.
Spring Cloud A microservice framework based on Spring Boot. It is not a certain technology, but an ordered collection of a series of microservice solutions or frameworks. It integrates mature and proven microservice frameworks on the market, and repackages them through the idea of ​​Spring Boot, shielding and adjusting the complex configuration and implementation principles, and finally provides developers with a set of simple, easy-to-understand and easy-to-deploy And an easy-to-maintain distributed system development kit.

Spring in a narrow sense: Spring Framework

    Spring in a narrow sense refers specifically to the Spring Framework, which we usually refer to as the Spring Framework.

    The Spring framework is a layered, one-stop lightweight solution for aspect-oriented Java applications. It is the core and foundation of the Spring technology stack and was created to solve the complexity of enterprise-level application development.

    Spring has two core parts: IoC and AOP.

core describe
IOC The abbreviation of Inverse of Control, translated as "inversion of control", refers to handing over the process of creating objects to Spring for management.
AOP The abbreviation of Aspect Oriented Programming, translated as "aspect-oriented programming". AOP is used to encapsulate the public behavior of multiple classes, and encapsulate the logic that has nothing to do with business but is commonly called by business modules, so as to reduce the duplication of code in the system and the coupling between modules. In addition, AOP also solves some system-level problems, such as logs, transactions, permissions, etc.

    Spring is a bean-based programming technology that is profoundly changing the Java development world. Spring uses simple and basic Java Beans to complete the work that only EJB could do before, making many complex codes elegant and concise, avoiding the bloated and inefficient development mode of EJB, and greatly facilitating the later maintenance and upgrading of projects and extensions.

    In actual development, server-side applications usually adopt a three-tier architecture, which are presentation layer (web), business logic layer (service), and persistence layer (dao).

    Spring is committed to the solution of each layer of Java EE application, and provides technical support for each layer.
    In the presentation layer, it provides the integration of Spring MVC, Struts2 and other frameworks;
    in the business logic layer, it provides the functions of managing transactions and recording logs;
    in the persistence layer, technologies such as MyBatis, Hibernate and JdbcTemplate can also be integrated to access the database.

    This fully reflects that Spring is a comprehensive solution, and Spring will never do repetitive things for those areas that already have better solutions.

    From the design point of view, the Spring framework gives Java programmers a higher degree of freedom and provides good solutions to common problems in the industry. Therefore, it is widely welcomed in the open source community and is regarded as a Java project by most companies. The preferred framework for development.

1.1.3 Features of Spring Framework

    The Spring framework has the following characteristics.

    Convenient decoupling and simplified development: Spring is a big factory, which can hand over the creation of all objects and the maintenance of dependencies to Spring management.

    Convenient integration of various excellent frameworks: Spring does not exclude various excellent open source frameworks, and provides direct support for various excellent frameworks (such as Struts2, Hibernate, MyBatis, etc.).

    Reduce the difficulty of using Java EE API: Spring provides packaging for some APIs (JDBC, JavaMail, remote calls, etc.) that are very difficult to use in Java EE development, which greatly reduces the difficulty of using these APIs.

    Convenient program testing: Spring supports JUnit4, and Spring programs can be easily tested through annotations.

    AOP programming support: Spring provides aspect-oriented programming, which can easily implement functions such as permission interception and operation monitoring of programs.

    Support for declarative transactions: transaction management can be completed only through configuration, without manual programming.

1.2 Spring architecture

    The Spring framework is a layered architecture. Each module can exist independently or be implemented jointly with other modules. Its architecture is shown in the following figure:

     Spring Core: The Core module is the core class library of Spring. All functions of Spring depend on this class library. Core mainly implements IOC functions, and all functions of Sprign are realized with the help of IOC.
    
    Spring AOP: The AOP module is Spring's AOP library, which provides support for aspect-oriented programming for objects managed by the Spring container.
    
    Spring DAO: Spring provides support for JDBC, encapsulates JDBC, allows JDBC to use Spring resources, and provides transaction management based on the AOP module.
    
    Spring ORM: Spring's ORM module provides management and auxiliary support for commonly used ORM frameworks. Spring supports commonly used frameworks such as Hibernate, ibtas, and jdo. Spring itself does not implement ORM, but only encapsulates common ORM frameworks. and manage it.
    
    Spring Context: The Context module provides a framework-style Bean access method, and other programs can access Spring's Bean resources through the Context. Added support for internationalization, event propagation, and validation, as well as support for many enterprise services and template framework integration.
    
    Spring Web: The WEB module is built on the Context module, providing a context suitable for Web applications. In addition, the integration of Spring and other Web frameworks (such as Struts1, Struts2, JSF) is also provided.
    
    Spring Web MVC: The WEB MVC module provides Spring with a set of lightweight MVC implementations. It is a full-featured Web application that accommodates a large number of view technologies, such as JSP, Velocity, and POI.

1.3 Understanding Inversion of Control and Dependency Injection

    IoC is the abbreviation of Inversion of Control, translated as "inversion of control". It is not a technology, but a design idea. It is an important object-oriented programming rule that can guide us how to design loosely coupled and better program.

    Spring manages the instantiation and initialization of all Java objects through the IoC container, and controls the dependencies between objects. We call a Java object managed by the IoC container a Spring Bean, which is indistinguishable from a Java object created using the keyword new.

    The IoC container is one of the most important core components in the Spring framework, which runs through the entire process of Spring from birth to growth.

1.3.1 Popular understanding

Address class:

public class Address {
    
    /**
     * 在Address类中使用到了String类与Integer类
     * 可以理解为,Address类依赖了String,Integer
     */
    private String city; //城市
    private String street; //街道
    private Integer no; //门牌号

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public Integer getNo() {
        return no;
    }

    public void setNo(Integer no) {
        this.no = no;
    }
}

Person class:

public class Person {
    /**
     * Person类依赖了String, Integer, Address类
     */
    private String name;
    private Integer age;
    private Address address;

    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 Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public void show(){
        System.out.println("hello");
    }
}

test:

public class SpringTest {
    @Test
    public void testNewObject() {
        //传统创建对象的方式:由代码编写者创建对象,对象的生命周期由程序员决定
        //根据对象定义位置的不同,对象的生命周期也不相同
        System.out.println("address对象的生命周期开始");
        if (true) {
            Address address = new Address();

            //使用对象
            address.setCity("郑州市");
            address.setStreet("迎春路");
            System.out.println(address.getCity());

            //如果把创建Address对象的代码放在if语句块中,那么if执行结束,我们可以认为对象生命周期就结束了
        }

        //System.out.println(address); //定义在if中,在if外无法使用address

        //如果Address对象放在test1()中,那么方法执行结束,我们可以认为对象生命周期就结束了
        System.out.println("address对象的生命周期结束");
    }

    @Test
    public void testIOC() {
        /*
         * 控制反转:IOC
         * 将创建对象的权力转交给Spring,由Spring来负责对象的创建、销毁和管理
         * 程序员无需创建对象,只需要从Spring容器中获取对象和使用对象即可
         */
    }

    @Test
    public void testDI() {
        Address address = new Address();

        /*
         * 首先我们理解什么是依赖:
         *  在Address类中使用到了String类与Integer类
         *  可以理解为,Address类依赖了String,Integer
         */
        //那么为依赖类型的属性赋值,就叫做依赖注入
        address.setCity("郑州市");
        address.setStreet("迎春路");
        address.setNo(18);

        Person p = new Person();
        //注入字面值
        p.setName(new String("张三"));
        p.setAge(new Integer(20));
        //注入其他的对象
        p.setAddress(address);
    }
}

1.3.2 Inversion of Control

    In traditional Java applications, if a class wants to call a property or method in another class, it usually creates the latter object in its code through new Object() before realizing the property or method. transfer. For the convenience of understanding and description, we can refer to the former as the "caller" and the latter as the "callee". In other words, the caller holds control over the creation of the callee object.

    But in the Spring application, the control of Java object creation is in the hands of the IOC container, and the general steps are as follows.
        1. Developers define Java objects through XML configuration files, annotations, Java configuration classes, etc., such as using <bean> tags in XML configuration files, using @Component annotations on Java classes, etc.
        
        2. When Spring starts, the IoC container will automatically create and manage these objects according to the object definition. These objects created and managed by the IOC container are called Spring Beans.
        
        3. When we want to use a certain Bean, we can get it directly from the IOC container (for example, through the getBean() method of ApplicationContext), without manually creating it through code (for example, the way of new Object()).

    The biggest change brought about by IoC is not at the code level, but a "master-slave transposition" change at the ideological level. Originally, the caller is the active party, and it will take the initiative to create whatever resource it wants to use; but in the Spring application, the IOC container holds the initiative, and the caller becomes the passive party, passively waiting for the IOC container Create the objects (Bean) it needs.

    This process has an inversion of control at the level of responsibility, and the creation of objects originally implemented by the caller through code is reversed to the IOC container for help. Therefore, we call this process Spring's "inversion of control".

1.3.3 Dependency Injection

    After understanding IoC, we also need to understand another very important concept: dependency injection.

    Dependency Injection (DI for short) was proposed by Martin Fowler in 2004 when explaining "Inversion of Control". Martin Fowler believes that the term "inversion of control" is very obscure, and it is impossible for people to directly understand "where is the inversion", so he suggests using "dependency injection" instead of "inversion of control".

    In object-oriented, there is a relationship called "dependency" between objects. Simply put, a dependency relationship is that an object needs to use another object, that is, there is an attribute in the object, and the attribute is an object of another class.

For example, there is a Java class named B whose code is as follows:

public class B {
    String bid;
    A a;
}

    It can be seen from the code that there is an object attribute a of type A in B, at this time we can say that the object of B depends on object a. And dependency injection is based on this "dependency relationship".

    We know that the core idea of ​​inversion of control is that Spring is responsible for the creation of objects. During the object creation process, Spring will automatically inject the object it depends on into the current object according to the dependency relationship, which is called "dependency injection".

1.3.4 How IOCs work

    In the Java software development process, there are more or less certain coupling relationships between objects in the system, between modules, and between software systems and hardware systems.

    If the coupling of a system is too high, it will cause problems that are difficult to maintain, but the code with no coupling at all can hardly complete any work, because almost all functions require the cooperation and interdependence between the codes to complete. Therefore, when we design programs, the idea we uphold is generally to minimize the degree of coupling without affecting the system functions.

    The bottom layer of IoC reduces the coupling degree of the code to a minimum through factory mode, Java reflection mechanism, XML parsing and other technologies. The main steps are as follows.
        1. In the configuration file (such as Bean.xml), configure each object and the dependencies between them;
        
        2. We can regard the IoC container as a factory, and the product of this factory is Spring Bean;
        
        3. When the container starts These configuration files will be loaded and parsed to obtain the basic information of objects and their dependencies;
        
        4. IoC uses Java's reflection mechanism to generate corresponding objects (that is, Spring Beans) according to class names, and converts this object according to dependencies Injected into objects that depend on it.

    Since the basic information of the object and the dependencies between objects are defined in the configuration file and not tightly coupled in the code, even if the object changes, we only need to modify it in the configuration file instead of Modify the Java code, which is the principle of Spring IoC decoupling.

1.4 Build Spring development environment

1.4.1 Create a Java project

    In the basic module of Spring, there is no Web-related content, and there is no need to create a JavaWEB project, just a Java project.

1.4.2 Import the core jar package

Core packages of the Spring framework:

name effect
spring-core-x.x.xx.jar Contains the basic core tool classes of the Spring framework, and other Spring components must use the classes in this package, which is the basic core of other components.
spring-beans-x.x.xx.jar Used by all applications, it contains all classes related to accessing configuration files, creating and managing beans, and performing Inversion of Control (IoC) or Dependency Injection (DI) operations.
spring-context-x.x.xx.jar Spring provides extended services based on basic IoC functions, and also provides support for many enterprise-level services, such as mail services, task scheduling, JNDI location, EJB integration, remote access, caching, and the encapsulation of various view layer frameworks.
spring-expression-x.x.xx.jar Defines Spring's expression language. It should be noted that when developing with Spring, in addition to the JAR package that comes with Spring, a third-party JAR package commons.logging is required to process log information.

Method 1: Import jar package

 Method 2: maven dependency configuration

<dependencies>
    <!-- spring核心包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springbeans包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springcontext包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring表达式包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

1.4.3 Writing Beans

HelloWorld.java

public class HelloWorld {
    
    public String show() {
        return "Hello Spring";
    }
}

1.4.4 Writing Spring configuration files

    applicationContext.xml is the default name, and its function is to configure the Bean objects that need to be managed by Spring in the SpringIOC container.
    
    Spring's configuration management can be configured using XML, and there is a concept of namespace in XML. In fact, it is a bit similar to the meaning of tags. After you give a namespace, the tags in the context of that namespace can be used in this XML file.
    
    1. beans: the root node of the xml file.
    
    2. xmlns: is the abbreviation of XML NameSpace, because the tag names of XML files are all customized, the tags written by oneself and defined by others are likely to be named repeatedly, but the functions are different, so a namespace needs to be added To distinguish this xml file from other xml files, similar to the package in java.
    
    3. xmlns:xsi: means that the xml file complies with the xml specification. The full name of xsi: xml schema instance refers to the specification that the elements defined in the schema resource file used in the specific application must comply with. That is, what standards do the elements defined in the file http://www.w3.org/2001/XMLSchema-instance comply with.
    
    4. xsi:schemaLocation: Refers to the specifications that the xml elements in this document comply with. These specifications are all formulated by the government. You can enter the website you wrote to see the version changes. The URL of the xsd can also help you determine whether the code you are using is legal.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring配置文件xml,采用schema约束规范(一个xml文件可以采用多个文件的规范) -->
<!--
	xmlns:扩展当前xml的规范
	xsi:schemaLocation:规范文件,成对出现
-->
<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:将Java中类的对象托管给springIOC容器 -->
    <bean id="helloworld" class="com.newcapec.bean.HelloWorld"></bean>
</beans>

The difference between Schema and DTD:

    Schema is the definition and description of the XML document structure, and its main function is to constrain the XML document and verify the validity of the XML document. The role of DTD is to define the legal building blocks of XML, which use a series of legal elements to define the document structure. The differences between them are as follows:

    1. Schema itself is also an XML document. DTD definition has nothing to do with XML. Schema has many benefits in understanding and practical application.

    2. The structure of the DTD document is "flat". If you define a complex XML document, it is difficult to grasp the nesting relationship between each element; the Schema document has a strong structure, and the nesting relationship between each element is very intuitive.

    3. DTD can only specify that the element contains text, and cannot define the specific type of element text, such as character type, integer type, date type, custom type, etc. Schemas are stronger than DTDs in this regard.

    4. Schema supports the description of the order of element nodes. DTD does not provide a description of disordered situations. To define disordered situations, all situations must be exhaustively arranged. Schema can use xs:all to represent unordered situations.

    5. Support for namespaces. DTD cannot take advantage of XML namespaces, and Schema satisfies namespaces very well. Moreover, Schema also provides include and import two methods of referencing namespaces.

    6. XML Schema cannot define entities like DTD, and is more complicated than DTD, but Xml Schema is now the standard of w3c organization, and it is gradually replacing DTD.

Schema benefits:

    1. When XML users use XML Schema, they do not need to relearn to understand XML Schema, which saves time;
    
    2. Since XML Schema itself is also a kind of XML, many XML editing tools, API development kits, and XML syntax analysis Filters can be applied directly to XML Schema without modification.
    
    3. As an application of XML, XML Schema naturally inherits the self-description and extensibility of XML, which makes XML Schema more readable and flexible.
    
    4. Since the format is exactly the same as XML, XML Schema can not only be processed like XML, but also be stored in the same way as the XML document it describes, which is convenient for management.
    
    5. The consistency between XML Schema and XML format makes it easy to exchange schemas between application systems that use XML as data exchange.
    
    6. XML has very high legality requirements. The description of XML in XML DTD is often used as a basis for verifying the legality of XML. However, the legality of XML DTD itself lacks a good verification mechanism and must be handled independently. XML Schema is different, it has the same legality verification mechanism as XML.

1.4.5 Testing

@Test
public void testSpringIOC() {
    //1、创建IOC容器ApplicationContext
    //ClassPathXmlApplicationContext是ApplicationContext接口的实现类,该对象通过加载类路径下面的spring配置文件
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

    //2、从容器中获取bean对象
    /**
         * Object getBean(String name)
         * 参数name: 获取对象的名称,对象的唯一标识符,bean标签的id属性值
         * 返回值Object: 对象
         */
    Object obj = ac.getBean("helloworld");
    System.out.println(obj instanceof HelloWorld);
    HelloWorld helloWorld = (HelloWorld) obj;
    String str = helloWorld.show();
    System.out.println("方法的返回值为:" + str);

    Object obj1 = ac.getBean("helloworld");

    System.out.println(obj == obj1);
}

There are two things to note about the above code:

  • The ClassPathXmlApplicationContext class is used when creating the ApplicationContext object. This class is used to load the Spring configuration file, create and initialize all objects (Bean).

  • The ApplicationContext.getBean() method is used to obtain the Bean, and the return value type of this method is Object, which is converted to an instance object of HelloWorld through mandatory type conversion, and the show() method in it is called.

Guess you like

Origin blog.csdn.net/ligonglanyuan/article/details/124567718