Spring learning summary (1): Introduction to Spring and simple cases

1. Introduction of Spring Framework

1. Introduction to Spring

       Spring is a layered Java SE/EE application full-stack lightweight open source framework, with IoC (Inverse Of Control) and AOP (Aspect Oriented Programming) as the core , providing the presentation layer Spring MVC And persistence layer Spring JDBC and business layer transaction management and many other enterprise-level application technologies, and can also integrate many famous third-party frameworks and class libraries in the open source world, gradually becoming the most used Java EE enterprise application open source framework.

       In actual development, we usually divide the server side into a three-tier architecture: presentation layer (web), business logic layer (service), and persistence layer (dao). Spring provides technical support for each layer, provides integration with Struts2 and Spring MVC framework in the presentation layer, manages transactions and log information records in the business logic layer, and integrates technologies such as Mybatis and Hibernate in the persistence layer.

       The Spring framework gives Java programmers a higher degree of freedom in design and provides good solutions to common problems in the industry. Therefore, it is extremely popular in the open source community and has gradually become the preferred framework for Java project development.

       Spring is not only a non-intrusive framework, but also a one-stop framework . So what is a non-intrusive framework? What is a one-stop framework?

       First, let's introduce non-invasive and invasive.

       When developing the program, if we use the framework. When using the framework, it is necessary to inherit the entity classes provided by the framework or implement the interfaces provided by the framework, which means that the framework is an intrusive framework, because the program itself depends on the framework. When the framework is removed, the program cannot run. This is the heavyweight framework we are talking about. For example, in struts1, action and actionForm must inherit the same as Action and ActionForm. On the contrary, non-intrusive framework is an important feature of lightweight frameworks, such as hibernate and spring. When we want to remove hibernate and Spring frameworks, we only need to modify the corresponding program and the program can still run. Simply put, non-intrusive means not inheriting the classes provided by the framework, but after dependency injection is completed through configuration, it can be used .

       The non-intrusive technology in Spring: allows free selection and assembly of the various functional modules of the Spring framework in the application system, and does not force the application system classes to inherit from or implement a certain class of the Spring framework system API interface.

       How to achieve non-intrusive design goals?

        The reflection mechanism is applied to provide various functions through dynamic invocation, and the BeanFactory between core groups is established.

       The BeanWrapper and BeanFactory component classes in the Spring framework are used together to finally achieve object instance creation and attribute injection.

       Advantages: Allow the developed application system to be freely transplanted in unused environments, without the need to modify the code that implements the core functions in the application system.

       Let me briefly talk about what is a one-stop framework?

       This is actually a beautiful word, describing that the Spring framework is very comprehensive and highly integrated. In short, it is all-encompassing. Many technologies can be integrated with Spring.

2. Spring's architecture

       The Spring framework adopts a layered architecture and is divided into multiple modules according to different functions. These modules can be roughly divided into Data Access/Integration, Web, AOP, Aspects, Messaging, Instrumentation, Core Container and Test, as shown in the following figure:

       Here are some brief introductions to these modules:

(1) Data Access/Integration (Data Access/Integration)

       The data access/integration layer includes JDBC, ORM, OXM, JMS and Transactions modules, which are introduced as follows.

      1) JDBC module: Provides a JDBC abstraction layer, which greatly reduces the coding of database operations in the development process.

      2)  ORM module: the integration layer provided by popular object-relational mapping APIs, including JPA, JDO, Hibernate and iBatis.

      3)  OXM module: Provides an abstract layer implementation that supports object/XML mapping, such as JAXB, Castor, XMLBeans, JiBX and XStream.

      4)  JMS module: Refers to the  Java  message service, which contains information for production and consumption.

      5) Transactions transaction module: support programming and declarative transaction management to implement special interface classes, and for all POJOs.

 (2) Web module

       Spring layer comprising a Web Web, S ervlet, and the Struts Portlet components are detailed below.

      1)  Web module: Provides basic Web development integration features, such as multi-file upload function, IoC container initialization of the Servlet listener used, and Web application context.

      2)   Servlet module: including Spring model-view-controller (MVC) to implement Web applications.

      3)  Struts module: Contains Spring applications in support classes, and integrates the classic Struts Web layer.

      4)  Portlet module: Provides the use of MV C implementation in the portlet environment, similar to the function of the Web-Servlet module.

(3) Core Container (core container)

       Spring's core container is the foundation established by other modules. It is composed of Beans module, Core core module, Context module and Expression Language module. The specific introduction is as follows.

       1) Beans module: Provides BeanFactory, which is a classic implementation of the factory pattern. Spring refers to the management object as Bean.

       2)  Core core module: Provides the basic components of the Spring framework, including IoC and DI functions.

       3)  Context Context module: Based on the core and Beans module, it is a medium for accessing definition and configuration of any object. The ApplicationContext interface is the focus of the context module.

       4)  Expression Language module: It is a powerful expression language for querying and operating object graphs at runtime.

(4) Test module

       Test module: Supports Spring components, uses JUnit or TestNG framework for testing, and provides support for application unit testing and integration testing.

(5) Other modules

       Other Spring modules include AOP, Aspects, and Instrumentation, which are introduced as follows.

       1)  AOP module: Provides an aspect-oriented programming implementation, allowing method interceptors and entry points to be defined, and code is separated according to functions to reduce coupling.

       2)  Aspects module: Provides integration with AspectJ. It is a powerful and mature aspect-oriented programming (AOP) framework.

       3)  Instrumentation module: Provides the support of class tools and the realization of class loader, which can be used in specific application servers.

       4)  Messaging module: Provides support for messaging system.

3. The composition of Spring

       Spring has seven modules, each of which exists independently. Modules and modules can be combined with each other, as shown in the figure below:

(1) Spring core container (Spring Core)

       The core container provides the basic functions of the Spring framework. The main component of the core container is BeanFactory, which is an implementation of the factory pattern. BeanFactory uses the Inversion of Control (IOC) model to separate the configuration and dependency specifications of the application from the actual application code.

(2) Spring Context (Spring Context)

       The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, verification and scheduling functions.

(3)Spring AOP

       Through configuration management features, the Spring AOP module directly integrates aspect-oriented programming functions into the Spring framework. Therefore, you can easily make the Spring framework manage any object that supports AOP. The Spring AOP module provides transaction management services for objects in Spring-based applications. By using Spring AOP, you can integrate declarative transaction management into your application without relying on components.

(4) Spring DAO

       The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exceptions follow the general DAO exception hierarchy.

(5) Spring ORM

       The Spring framework inserts several ORM frameworks to provide ORM object relational tools, including JDO, Hibernate and iBatis SQL Map. All of these follow Spring's general transaction and DAO exception hierarchy.

(6) Spring Web module

       The Web context module is built on top of the application context module to provide context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The web module also simplifies the work of processing multipart requests and binding request parameters to domain objects.

(7) Spring MVC framework

       The Spring  MVC framework is a full-featured MVC implementation for building Web applications. Through the strategy interface, the MVC framework becomes highly configurable, and MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, iText, and POI.

 4. Advantages of Spring

       (1) Facilitate decoupling and simplify development. Spring is a big factory that can delegate the creation of all objects and the maintenance of dependencies to Spring for management.

       (2) Facilitate the 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.).

       (3) Reduce the difficulty of using Java EE API. Spring provides encapsulation for some very difficult APIs (JDBC, JavaMail, remote calls, etc.) in Java EE development, which greatly reduces the difficulty of these API applications.

       (4) It is convenient to test the program. Spring supports JUnit4, and Spring programs can be easily tested through annotations.

       (5) AOP programming support. Spring provides aspect-oriented programming, which can easily implement functions such as program permission interception and operation monitoring.

       ( 6) Support for declarative transactions. Only need to configure to complete the management of the transaction, without manual programming

Two, Spring's simple entry case

       Under normal circumstances, the way we create an object is done through new, such as: User user = new User(). So, in the next case, how to use Spring to complete the creation of the object and call its methods?

1. Case steps

(1) Create a maven project.

(2) Introduce Spring5 related jar packages, including: spring-core, spring-beans, junit, spring-context, spring-expression, commons-logging.

(3) Create the User class and define the showMessage() method.

(4) Create bean.xml under resources and configure bean object in xml.

(5) Perform unit testing.

       1) Load the configuration file bean.xml

       2) Get the bean object.

       3) Call the showMessage() method.

2. The realization process

       First, create a maven project and introduce Spring related jar packages in pom.xml, as follows:

<dependencies>
  <!--    单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

       For the function of these jar packages, please refer to this blog: https://www.cnblogs.com/fmling/p/5979840.html

       Create the User class as follows:

public class User {

    public void showMessage(String name, Integer age){
        System.out.println("name is : " + name + ", age is : " + age);
    }
}

       Create bean.xml in the resources directory and configure the User class as follows:

<?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">
    <!-- 配置User
        <bean> 配置需要创建的对象
            id :用于之后从spring容器获得实例时使用的,可以随便取名,如:aa、abc
            class :需要创建实例的全限定类名
    -->
    <bean id="user" class="com.yht.example1.entity.User"></bean>
</beans>

       Create a User object through Spring and call its methods:

public class UserTest {
    @Test
    public void testUser(){
        //加载Spring配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //通过配置文件中bean的id获取bean对象
        User user = (User) applicationContext.getBean("user");//参数与bean.xml中配置的id值一致
        //调用showMessage()方法
        user.showMessage("tom", 23);
    }
}

       The execution results are as follows:

        We just mentioned that the id of the bean in bean.xml can be named arbitrarily, so is it really possible? Next we will test it.

       Change the id of the bean to abc, and then test.

<bean id="abc" class="com.yht.example1.entity.User"></bean>
User user = (User) applicationContext.getBean("abc");

       The result of the execution is still: name is: tom, age is: 23.

3. Main points

       In Spring, the entity class object must have a default no-parameter structure, otherwise bean.xml will report an error.

       Here can be a simple test, give a private attribute name in the User class, and provide a parameter structure. At this time, an error will be reported in bean.xml.

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/112705962