Programming Architecture (08): Spring.Mvc.Boot framework

Source code of this article: GitHub·click here || GitEE·click here

One, Spring framework

1. Framework overview

Spring is an open source framework. One of the main advantages of the framework is its layered architecture. The layered architecture allows users to choose which component to use while providing an integrated framework for J2EE application development. Spring uses basic JavaBeans to accomplish things that could only be done by EJB before. Spring is a layered lightweight open source framework.

Basic features: layered architecture, high cohesion and low coupling, support AOP programming, transaction management, integration testing, integration of various frameworks.

2. Core components

Core container : Contains Bean creation, configuration, management and other functions.

AOP aspect programming : can help decoupling applications.

Data access : Integrated JDBC, commonly used Dao layer framework hibernate, mybatis, etc.

Web programming : MVC framework of integrated process, to realize the separation of interface logic and application.

3. Bean object understanding

The Spring container is responsible for creating, assembling, setting properties, and then managing objects throughout the life cycle, called Bean objects.

Assembly method : XML format, annotation scanning, Java code assembly.

Scope : used to determine the number of bean instances created by spring, such as singleton beans and prototype beans. Singleton default singleton, prototype multiple instances, request request, session session level, global-session.

Life cycle : instantiation, attribute loading, management before and after initialization, and destruction.

4. Commonly used core annotations

Controller: Mark a class as Handler, based on @Mapping related solutions (@GetMapping, @PostMapping, @PutMapping, @DeleteMapping) to associate the mapping relationship between the request and the Controller method, so that the Controller can be accessed by request.

RequestMapping: Processing annotations for request address mapping, which can be applied to classes or methods. Used on the class, it means that all methods in the class that respond to the request use the address marked on the class as the parent path.

Resource: Inject automatically according to ByName, need to import package javax.annotation.Resource. @Resource has two important attributes: name and type. Spring parses the name attribute annotated by @Resource as the name of the bean, and the type attribute parses as the type of the bean.

Service: It can replace the Bean management of a specific configuration file. The defined bean is singleton by default, and the default name is the class name and the first letter is lowercase.

5. IOC and DI ideas

IOC container

The object coupling relationship in the Java system is very complex. The dependencies between the various modules of the system and the mutual call requests between the microservice modules are all this truth. Reducing the degree of coupling between system modules, objects, and services of microservices is one of the core issues of software engineering. Because the core idea in the Spring framework is IOC control inversion, which is used to achieve decoupling between objects.

Dependency injection

The action of IOC to directly establish relationships between objects is called DI Dependency Injection; Dependency: Object A needs to use the functions of Object B, so Object A is called Object B. Injection: Instantiate object B in object A to use the function of object B. This action is called injection.

6. Aop aspect programming

A technology that realizes the unified maintenance of program functions through pre-compilation and runtime dynamic agents. Core role: It can isolate various parts of business logic, thereby reducing the coupling between various parts of business logic and improving program reusability and development efficiency. AOP provides a new solution to replace inheritance and delegation, and it is more concise and clear to use. It is a hot concept in software development.

Implementation method : JDK dynamic proxy, CgLib bytecode enhancement, Spring semi-automatic proxy, Spring automatic proxy.

7. Transaction management

A transaction refers to a series of operations (SQL statements) performed as a single logical unit of work. These operations are either all successful or all unsuccessful. The essence of Spring transaction management is to encapsulate the operations that the database supports for transactions. Using the JDBC transaction management mechanism is to use the java.sql.Connection object to complete the commit and rollback of the transaction.

Core API package

PlatformTransactionManager: Platform transaction manager, Spring manages transactions. When transaction configuration must be performed using the transaction manager, the core methods: get the transaction, commit the transaction, and roll back the transaction.

TransactionDefinition: This object encapsulates transaction details (transaction definition, transaction attributes), such as isolation level, read-only, timeout, etc.

TransactionStatus: used to record the current transaction status. For example: whether there is a save point and whether the transaction is completed. Spring bottom layer performs corresponding operations according to the state.

8. Configuration file

In the Spring configuration file, the following core content is usually configured;

  • Read external configuration files, such as JDBC parameters;
  • Configure the database connection pool, such as Druid, C3P0, etc.;
  • Integrated environment configuration, such as SSM or SSH integration;
  • Control methods for managing Transaction;
  • Integrate common components, such as mail, tasks, MQ, etc.;

In actual development, complex project configuration is very complicated and difficult to manage. There may be dozens of configuration files involved in different environments in the project, which are simplified in a unified agreement in the SpringBoot framework.

9. The environment integrates SSM and SSH

The Spring framework aggregates strong integration capabilities, such as the common integration of Mybatis, Mvc, Hibernate, Redis and other series of components, which provides great convenience for the integration of the development environment. The overall responsibilities are divided into several layers: control layer, business logic layer, The data persistence layer, domain module layer, and middleware layer help developers to build web applications with clear structure, good reusability, and easy maintenance in a short time.

10. Design patterns

Singleton mode: The management of Bean objects in the Spring framework is singleton by default, and it can also be explicitly identified as multiple instances.

Factory mode: Generate class objects through corresponding factories. This design method conforms to the "open and close" principle. The usage of BeanFactory and Bean in Spring framework.

Adapter mode: In SpringMvc execution control, the front controller DispatcherServlet calls the processor adapter to execute the Handler, the processor adapter executes the Handler, and returns the ModelAndView to the adapter.

Responsibility chain mode: DispatcherServlet core method doDispatch. HandlerExecutionChain just maintains the collection of HandlerInterceptor, can register the corresponding interceptor to it, it does not directly process the request itself, the request is assigned to the registered processor on the responsibility chain for execution, reducing the degree of coupling between the responsibility chain itself and the processing logic.

Two, SpringMvc mode

1. Mvc model concept

SpringMVC is a request-driven lightweight web framework based on the MVC design pattern implemented in Java. It comes from the Spring Framework Family Bucket, seamlessly integrates with the Spring Framework, uses the idea of ​​MVC architecture pattern, and decouples the Web layer's responsibilities. . The structure is loose, almost all kinds of views can be used in SpringMVC, each module is separated and the coupling is very low, and it is easy to expand. Seamless integration with Spring, simple, flexible, and easy to use.

2. Execution process

Initiate a request to the front controller DispatcherServlet; the front controller requests HandlerMapping to find, Handler can find according to xml configuration and annotations;

The processor mapper HandlerMapping returns Handler to the front controller; the front controller calls the processor adapter to execute the Handler; the processor adapter executes the Handler;

Handler execution is complete and returns ModelAndView to the adapter; the processor adapter returns ModelAndView to the front controller. ModelAndView is a low-level object of the springmvc framework, including Model and view;

The front controller requests the view resolver to resolve the view, and resolves it into a real view according to the logical view name; the view resolver returns the View to the front controller; the front controller performs the view rendering, and the view rendering uses the model data (in the ModelAndView object) Fill in the request field; the front controller responds to the user with the result;

3. Core components

Front controller: After the request leaves the browser, the first thing that arrives is the DispatcherServlet, which is the center of the entire process control.

Processor mapper: Route to the specified interface according to the requested url, and the user requests to find the Handler processor.

Processor adapter: Handler is executed according to specific rules, supports multiple processors, and the processing methods in each processor are different.

Processor: Processing user requests, involving specific business logic, needs to be developed according to business requirements.

View resolver: Generate View from the response result of the request, and resolve it into a physical view name according to the logical view name, which is the specific page address.

View: Mvc framework provides support for many types of View views, including: jsp, freemarker, pdf, etc.

4. Parameter processing

requestParam: Mainly used to obtain parameters in the control layer of the SpringMvc framework. Three commonly used parameters: defaultValue means to set the default value, required to set whether it is a parameter that must be passed in through the boolean, and value value means the name of the passed in parameter.

RequestBody: For receiving the Json string data passed to the backend in the request body, there is no request body in the GET method, so when using @RequestBody to receive data, you cannot use the GET method to submit the data, and you need to use the POST method to submit.

ResponseBody: This annotation is used for the return object of the method. You can configure the converter to specify the data response format. If you want the returned data to be used when you specify the data format instead of the View page, such as Json, Xml, etc.

5. Integrate the Spring framework

  • Configure scan interface file;
  • Start the MVC default annotation mapping method;
  • Configure the view resolver;
  • Web.xml configuration loads Spring-Mvc files;

6. Compare WebFlux

Reactive programming is a declarative programming paradigm based on data flow and change transfer. WebFlux is a component of web control-side reactive programming. It is explained on the Spring official website. It is not intended to replace SpringMvc, but to provide more The solution of the scene.

Three, SpringBoot framework

1. Common basic functions

  • Environment construction and annotation start mechanism, log printing;
  • Global exception handling, use of timing tasks and asynchronous tasks;
  • Interceptor configuration, AOP aspect programming, file management;
  • Integrate common security components such as JWT, Shiro and Security;
  • Integrated Actuator monitoring components, system packaged operation;

2. Integrate data sources

  • Integrate JdbcTemplate, JPA, multiple data source configuration;
  • Integrate common connection pools for Druid and C3P0;
  • Integrate Mybatis framework, integrated paging management;

3. Integrate common middleware

  • Integrated Redis cache, Cache annotation mode;
  • Integrate ElasticSearch framework to realize high-performance search engine
  • Based on Swagger2, build an interface management interface;

The entire SpringBoot framework is based on many conventions and specifications on the Spring framework. The underlying principles have not changed. It is more familiar with various usages, and you will understand it with more.

Four, comparative analysis

The Spring framework is the lowest level implementation principle relative to the Spring open source ecology. SpringMvc is based on it and mainly simplifies the development of the Web control layer. For example, the previous Struts and Servlet are gradually replaced.

On the basis of Spring+Mvc, SpringBoot implements a very powerful agreement configuration, integrates the agreement in a complex environment, simplifies development and configuration, and business development remains the same. In the SSM environment, no matter whether the project configuration starts and debugs, it is very complicated. , It has been continuously simplified after reaching the SpringBoot level, so SpringBoot learning is basically easy to use after understanding the agreed configuration specifications.

Five, source code address

GitHub·地址
https://github.com/cicadasmile
GitEE·地址
https://gitee.com/cicadasmile

Recommended reading: finishing programming system

Serial number project name GitHub address GitEE address Recommended
01 Java describes design patterns, algorithms, and data structures GitHub·click here GitEE·Click here ☆☆☆☆☆
02 Java foundation, concurrency, object-oriented, web development GitHub·click here GitEE·Click here ☆☆☆☆
03 Detailed explanation of SpringCloud microservice basic component case GitHub·click here GitEE·Click here ☆☆☆
04 SpringCloud microservice architecture actual combat comprehensive case GitHub·click here GitEE·Click here ☆☆☆☆☆
05 Getting started with SpringBoot framework basic application to advanced GitHub·click here GitEE·Click here ☆☆☆☆
06 SpringBoot framework integrates and develops common middleware GitHub·click here GitEE·Click here ☆☆☆☆☆
07 Basic case of data management, distribution, architecture design GitHub·click here GitEE·Click here ☆☆☆☆☆
08 Big data series, storage, components, computing and other frameworks GitHub·click here GitEE·Click here ☆☆☆☆☆

Guess you like

Origin blog.csdn.net/cicada_smile/article/details/109093878