preface
The Spring framework is becoming more and more popular now, you can miss other frameworks, but Spring must not be missed!
1 Spring core components
In a word: Spring is a lightweight, non-invasive inversion of Control (IoC) and AOP framework.
PS: The current standard configuration of Java development is Spring5 + Spring Boot 2 + JDK 8
1.1 introduction of Spring
Nowadays, Java development is also referred to as Spring development. Spring is the first major framework in Java. It makes the existing technology easier to use, promotes good programming habits, and greatly simplifies the development of applications.
Because if you think about it, if we want to implement a certain function, the amount of code is usually fixed, and we can either write it all by ourselves or use the existing excellent framework. Spring has provided us with various excellent components, but also provides a good code organization logic and business development process specification framework. Its main advantages are as follows:
- IOC and DI support
Spring is a large factory container that allows all object creation and dependency maintenance to be managed by Spring. The Spring factory is used to generate beans and manage their life cycle, implementing the design concept of high cohesion and low coupling.
- Support for AOP programming
Spring provides section-oriented programming, which can facilitate the implementation of programs for permission interception, running monitoring and other functions.
- Support for declarative transactions
Transactions can be managed through configuration without manual programming, and some of the JDBC operations that have been repeated before do not need to be written.
- Convenient program testing
Spring provides support for Junit4, making it easy to test Spring programs with annotations.
- Adhesive function
It is easy to integrate excellent frameworks. Spring does not exclude excellent open source frameworks and provides direct support for excellent frameworks such as Struts, Hibernate, MyBatis, Quartz, etc.
- Reduce the difficulty of using JavaEE apis
Spring provides a wrapper around some of the most difficult apis in JavaEE development (JDBC, JavaMail, remote calls, etc.), which makes it much easier to use.
1.2 Spring components
The Spring framework exists in modules. Except for Spring Core Container, which is the most essential module, all modules are optional. There are about 20 modules.
The Spring framework has many features, made up of seven well-defined modules.
Spring Core: The Spring Core, the most basic part of the framework, provides IOC and DI features.
Spring Context: The Spring Context container, which is a BeanFactory enhanced subinterface.
Spring Web: It provides support for Web application development.
Spring MVC: It is an implementation of the MVC idea in Web applications.
Spring DAO: Provides an abstraction layer for JDBC, simplifying JDBC coding and making coding more robust.
Spring ORM: It supports integration for popular ORM frameworks, such as Spring + Hibernate, Spring + iBatis, Spring + JDO integration, etc.
Spring AOP: Aspect oriented programming, which provides a programming implementation that is compatible with the AOP consortium.
2 the IOC and AOP
The two topics that Spring will never talk about are IOC and AOP. These are the two core topics of Spring. Beginners should not be intimidated by the terms IOC, AOP, Aspect, Pointcut, and Advisor, all of which are coined by boring people to write papers.
2.1 the IOC
Java is an object-oriented programming language. Generally, an application is composed of business logic developed by a group of objects cooperating with each other. How do you manage these objects?
Abstract factory and factory method design patterns can help us create objects, and generator patterns can help us deal with the dependencies between objects, but these require us to create other factory and generator classes, and we have to manage these classes, adding to our burden. Concern public number: Kirin bug, get a detailed Java interview question manual, covering 25 core technical points, welcome to exchange, like the article remember to pay attention to me like yo, thank you for your support! If the application can automatically manage the object’s declaration cycle when the object needs it, we don’t have to manage the Bean’s declaration cycle ourselves, which is decoupling.
Spring presents the idea that Spring is responsible for controlling the life cycle of objects and the relationships between them. All classes will be registered in the Spring container, telling Spring what the class is and what it needs, and Spring will voluntarily give you what you need when the system is running properly, as well as handing you over to other beans that need you.
The creation and destruction of all classes is controlled by Spring, which means that it is not the reference object that controls the life cycle of an object, but Spring. For a specific object, it used to control other objects, but now all objects are controlled by Spring, so this is called Inversion of Controller, or Dependency Injection DI.
Given the general idea, if you try to implement IOC yourself, you’ll find that the core is reflection + XML parsing/annotation parsing.
Read XML to get bean information, class information, attribute value information.
Get the constructor of the target class through reflection, call the constructor, and assign a value to the object.
If you want to follow the source code you will find that the source entry of IOC is refresh(), which contains 13 functions to provide different functions, the specific process is more complex, public number reply IOC to obtain the original image.
2.2 the Context
The IOC container only provides space for managed objects. How do we put objects into the container that we need the container to manage for us? This involves the Spring application Context.
Application Context:
Based on Core and Beans, it provides a number of extensions, including internationalization operations (based on JDK), resource loading (based on JDK Properties), data validation (a data validation mechanism that Spring encapsulates itself), data binding (spring-specific, The parameters in the HTTP request are directly mapped as POJOs, type conversion, and the ApplicationContext interface is the core of Context, which can be understood as the Context or background information of the Bean.
It is easy to understand that the ApplicationContext is an abstract representation of the Spring container, and the common ApplicationContext is essentially a high-level interface that maintains Bean definitions and collaboration between objects. The Spring framework itself provides a number of container implementations, which fall into two categories:
- One is the less commonly used BeanFactory, which is the simplest container that provides only basic DI functionality.
- The other is the ApplicationContext derived from the BeanFactory. Its abstract interface is the ApplicationContext mentioned above, which can provide more enterprise-level services, such as parsing configuration text information, and so on. This is also the most common application scenario of ApplicationContext instance objects. With context objects, we can register objects with the container that need to be managed by Spring. For context abstraction interfaces, Spring also provides several types of container implementations that we can choose from in different application scenarios.
AnnotationConfigApplicationContext: from one or more configuration based on Java class loading context definition, apply to the way Java annotations.
ClassPathXmlApplicationContext: from the classpath of one or more XML configuration file loaded context definition, apply to the XML configuration.
FileSystemXmlApplicationContext: from the file system under one or more XML configuration file loaded context definition, that is to say, in the system drive load XML configuration files.
AnnotationConfigWebApplicationContext: for web applications, suitable for comments.
XmlWebApplicationContext: Loads context definitions from one or more XML configuration files in a Web application for XML configuration.
Work through XML configuration or annotations to configure the beans to be managed and the collaboration between the beans. Then load the application Context object into the Spring container, and the container can provide your application with the object management service you want. Such as tracking the ClassPathXmlApplicationContext underlying source code:
As you can see that parsing an XML file can be extended up to eight layers, you can see that the Spring container takes a holistic approach to implementing IOC.
2.3 AOP
If we want to code the calculator function, our goal is to realize the operation of addition, subtraction, multiplication and division, but how to print the log and verify the number compliance before and after each operation?
Separate reusable functional modules for logging and data validation, and then dynamically embed and execute this code where appropriate in the execution of the program. This simplifies code writing.
The business logic code does not have the code of parameters and general logic, and the business module is more concise and only contains the core business code. The code separation of business logic and general logic is realized, which is easy to maintain and upgrade, and reduces the coupling of business logic and general logic.
The code must be loaded into memory to implement the new object, so if we extract the reusable function, and then implement the common function in memory to construct a new object, it is OK.
Spring AOP(Aspect Oriented Programming) provides just another way to think about program structure to improve object-oriented Programming. If the purpose of dependency injection is to keep components cooperating with each other in a looser coupling state, AOP separates functionality across applications into reusable components. A technique for dynamically adding functionality to a program without modifying the source code at compile, load, or run time. Thus realize the isolation of business logic, improve the modular ability of code.
The core of AOP is actually dynamic proxy, if it is to achieve the interface then will use JDK dynamic proxy, otherwise use CGLIB proxy, mainly applied to deal with some crosscutting nature of system-level services, such as log collection, transaction management, security check, cache, object pool management, etc..
Spring mainly provides aspects, JoinPoint join points, PointCut pointcuts, Advice enhancements and other implementations. AOP generally has five ways to surround:
Pre-notification (@before)
Return notification (@afterRETURNING)
Exception Notification (@afterThrowing)
Post notification (@after)
Circular notification (@around) :(highest priority)
PS: In the case of multiple facets, you can use @order to specify the sequence. The smaller the number, the higher the priority.
3 Differences between JDK dynamic proxies and CGLIB proxies
JDK dynamic proxies and CGLib dynamic proxies are both the basis for implementing Spring AOP, and they are implemented in different ways.
3.1 JDK Dynamic Proxy
The characteristics of
Interface: For JDK dynamic proxies, business classes need an Interface.
Proxy: The Proxy class is dynamically generated. This class generates an instance of Proxy after calling the proxy.newProxyInstance () method. In fact, the Proxy class also exists, not just the instance of the class, but the Proxy class can be stored on the hard disk.
Method: Each Method of the business delegate class is now not statically displayed in the Proxy class.
InvocationHandler: This class first invokes the Invoke method when the business delegate class executes. The Invoke method performs the desired proxy operation, enabling repackaging of the business method.
Conclusion:
The JDK dynamic proxy class implements the InvocationHandler interface and overrides the Invoke method.
The basis of JDK dynamic proxies is reflection (method.invoke(object, parameter)) proxy.newProxyInstance ()
3.2 CGLib dynamic proxy
Features:
Using the bytecode processing framework ASM, its principle is to create a subclass for a class through bytecode technology, and in the subclass using method interception technology to intercept all calls to the parent class method, along with the potential woven into crosscutting logic.
Dynamic proxy objects created by CGLib perform much better than those created by JDK. However, CGLib takes much longer to create proxy objects than the JDK, so for singleton objects, CGLib works better than JDK because you don’t need to create objects frequently. At the same time, because CGLib is subclassed dynamically, there is no proxy for final methods.
Note:
Unlike JDK dynamic proxies, which can only do this for interfaces, CGlib can either do this for classes that don’t implement interfaces or for classes that implement interfaces.
3.3 Code implementation part
Common code:
Public interface FoodService {public void makeNoodle(); public void makeChicken(); Public implements FoodService {@override public void makeNoodle() {public implements FoodService {@override public void makeNoodle() { System.out.println("make noodle"); } @Override public void makeChicken() { System.out.println("make Chicken"); }}Copy the code
JDK dynamic proxy code:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKProxyFactory implements InvocationHandler { private Object target; public JDKProxyFactory(Object target) { super(); this.target = target; Public Object createProxy() {// 1. ClassLoader ClassLoader = target.getClass().getClassLoader(); // 2. Get the object's implementation interface Class<? >[] interfaces = target.getClass().getInterfaces(); Object newProxyInstance = proxy. newProxyInstance(classLoader, interfaces, this); return newProxyInstance; } // First argument: proxy object. Generally not used; The second parameter: the method to be enhanced; @override public Object invoke(Object proxy, Method Method, Object[] args) throws Throwable {system.out.println (" this is an enhanced method before......" ); Object invoke = method.invoke(target, args); System.out.println(" This is enhanced method after......" ); return invoke; } public static void main(String[] args) { // 1. FoodServiceImpl foodService = new FoodServiceImpl(); // create proxy object JDKProxyFactory proxy = new JDKProxyFactory(foodService); FoodService createProxy = (FoodService) proxy.createProxy(); createProxy.makeChicken(); }}Copy the code
Cglib dynamic proxy code:
import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; Public class CglibProxyFactory implements MethodInterceptor {private Object target; Public CglibProxyFactory(Object target) {super(); this.target = target; Public Object createProxy(){//1. Create Enhancer Enhancer = new Enhancer(); //2. Pass the target object's class enhancer.setsuperclass (target.getClass()); //3. Set the callback to enhancer.setcallback (this); return enhancer.create(); } // Parameter one: proxy object; Parameter 2: method to be enhanced; Parameter 3: parameters that need to be enhanced; @override public Object Intercept (Object proxy, Method Method, Object[] args, MethodProxy MethodProxy) throws Throwable {system.out.println (" this is an enhanced method before......" ); Object invoke = methodProxy.invoke(target, args); System.out.println(" This is enhanced method after......" ); return invoke; } public static void main(String[] args) { // 1. FoodServiceImpl foodService = new FoodServiceImpl(); CglibProxyFactory proxy = new CglibProxyFactory(foodService); FoodService createProxy = (FoodService) proxy.createProxy(); createProxy.makeChicken(); }}Copy the code
Spring AOP differs from AspectJ AOP
4.1 Spring AOP
Spring AOP is a runtime enhancement with the following features:
- Based on dynamic proxy implementation, the default interface, using the DYNAMIC proxy provided by JDK implementation, if the method is CGLIB implementation
- Spring AOP needs to rely on the IOC container to manage and can only work with the Spring container, implemented using pure Java code
- In terms of performance, Spring AOP’s performance is not as good as AspectJ’s because it is implemented based on dynamic proxies, which require generating proxy instances at container startup and add stack depth to method calls.
- Spring AOP addresses the most common type of AOP(method weaving) in enterprise development.
4.2 the AspectJ
AspectJ is an easy-to-use, powerful AOP framework that is compile-time enhanced and can be used alone or integrated into other frameworks, making it a complete solution for AOP programming. AspectJ requires a separate compiler, AJC.
AspectJ is static weaving, which is implemented by modifying the code to finish weaving before it is actually run, so it generates classes with no extra runtime overhead. There are usually several times to weave:
- Compile-time weaving: If class A adds an attribute using AspectJ and class B references it, the scenario needs to be compile-time weaving otherwise class B won’t Compile.
- Post-compile weaving: that’s where the.class file is generated, or the weaving jar file is generated, and we need to improve the weaving.
- Load-time weaving: Weaving occurs when classes are being loaded, and there are several common ways to do this
4.3 contrast
5. The BeanFactory and FactoryBean
5.1 the BeanFactory
- BeanFactory ends with Factory, indicating that it is a Factory class (interface). BeanFacotry is the primitive Factory in Spring.
- BeanFactory does not support many of Spring’s plug-ins, such as AOP functionality, Web applications, and so on. The ApplicationContext interface, derived from the BeanFactory interface, provides international access, event propagation, and more.
- The BeanFactory, the core of the IOC container, is responsible for producing and managing Bean objects.
5.2 FactoryBean
- A FactoryBean ends in Bean to indicate that it is a Bean.
- A FactoryBean is a factory-class interface that you can implement to customize the logic of instantiating the Bean. The FactoryBean interface plays an important role in the Spring framework. Spring itself provides over 70 FactoryBean implementations.
- When a Bean in an IOC container implements a FactoryBean, the Bean object obtained by getBean(String BeanName) is not an implementation of the FactoryBean. It is the object returned by the getObject() method in the implementation class. To get the implementation class of a FactoryBean, getBean(String &BeanName) is preceded by an &.
6. Spring lifecycle
The process of Spring IOC initialization and destruction of beans can be roughly divided into four parts: Bean definition, Bean initialization, Bean lifetime and Bean destruction.
The problem is that Spring provides a series of interfaces and configurations to complete the Bean initialization process if we want to fulfill our custom requirements. Take a look at the entire IOC container initialization Bean process.
In general, there are three initialization and destruction methods for custom beans:
- Configuration via XML or @bean
Do this using XML or @bean (initMethod=”init”, destroyMethod=”destory”).
- This is implemented using two annotations (the Java specification) defined by the JSR250 rules
PostConstruct: An annotation in the JDK specification to initialize a Bean after it has been created and belongs to an assignment.
PreDestroy: Notify the bean before it will be removed and clean up before the container is destroyed.
Tip: JSR is a set of specifications provided by the JDK.
- Implement class methods through inheritance
Implement the afterPropertiesSet() method of the InitializingBean interface, which will be called after the beanFactory has created the object and all the bean properties have been set, which is equivalent to the initialization method.
Implement the destory() method to DisposableBean, which will dispose of the singleton bean when it is destroyed
For single-instance beans, the initialization and destruction methods can be invoked normally. For multi-instance beans, the container is only responsible for initialization on invocation, but does not manage the bean, and does not call destruction when the container is closed.
7. Design patterns in Spring
Different types of design patterns are widely used in the Spring framework. Let’s take a look at what are some of them?
- Factory Design pattern: Spring uses the factory pattern to create bean objects from the BeanFactory, ApplicationContext.
- Proxy design pattern: Implementation of Spring AOP functionality.
- Singleton design pattern: Beans in Spring are singleton by default.
- Template method pattern: Spring’s jdbcTemplate, hibernateTemplate, and other classes that end in Template for database operations use the Template pattern.
- Wrapper design pattern: Our project needs to connect to multiple databases, and different customers need to access different databases on each visit. This pattern allows us to dynamically switch between different data sources based on customer needs.
- Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern.
- Adapter pattern: The adapter pattern is used in Spring AOP enhancements or Advice, and is used in Spring MVC to adapt controllers.
8. Spring loop dependencies
8.1 Circular dependency in a nutshell
Spring loop dependencies: Basically, there are direct or indirect dependencies between one or more object instances that constitute a ring call. There are two prerequisites for cyclic dependencies to occur:
The beans that have loop dependencies must be singletons, not at all if you rely on Prototype.
Dependency injection can’t be all constructor injection, it can only solve the circular dependency of setter methods, which is a mistake.
Assuming that AB is interdependent, the following conclusions can be drawn after different injection methods are tried:
PS: The reason the fourth one works and the fifth one doesn’t is that Spring creates beans in A natural order by default, so A is created before B.
8.2 Circular dependency is colloquial
Spring addresses cyclic dependencies with level 3 caching.
- Level 1 cache: Map
,object>
singletonObjects, singleton pool, used to hold instantiated, injected, and initialized bean instances
- Level 2 cache: Map
,object>
earlySingletonObjects, early exposure objects, used to hold instantiated bean instances
- Map
,objectfactory>
> singletonFactories, an early exposure object factory that holds bean creation factories so that later extensions have a chance to create proxy objects.
When A, B two kind of circular reference occurs, after A complete instantiation, just use the instantiated object to create an object factory, and added to the three-level cache, if A is AOP agent, then through access to the factory is A proxy objects, if A is not AOP agent, then get to the factory is A instantiation of the object. When A does property injection, B will be created, and B will depend on A, so when B is created, getBean(A) will be called to get the required dependency, and getBean(A) will get the required dependency from the cache:
The first step is to get the factory in the level 3 cache.
The second step is to call the getObject method of the object factory to get the corresponding object, which is then injected into B. B then goes through its lifecycle, including initialization, post-processor, and so on.
After B is created, B is injected into A, and A completes its life cycle. This is the end of the loop dependency!
8.3 What is the significance of three-level Caching?
To track the source (pictured above), pay attention to during the process of tracking under different AOP with no dependence on AOP depend on two things, you will find that the three levels of cache after tracking function is the only true circular dependencies occurs, to generate a proxy object in advance, otherwise will only create a factory and puts it into the triple cache, But you don’t actually create objects through this factory. As for speeding up, pull the switch.
As shown in the figure above, using level 2 caching to resolve cyclic dependencies means that all beans will complete the AOP proxy once they are instantiated, which violates Spring’s design principles. Spring at the beginning of the design is in Bean through AnnotationAwareAspectJAutoProxyCreator this post processor to the life cycle of the last step to complete the AOP agent, instead of immediately after the instantiation to AOP agent.
9. The Spring transaction
The essence of Spring transactions is the transaction support of the database. Without the transaction support of the database, Spring cannot provide transaction functionality. Spring only provides a unified transaction management interface, the specific implementation is implemented by each database itself, database transaction submission and rollback is through binlog or Undolog implementation, the specific process in MySQL described. Spring adjusts the database isolation level at the start of a transaction based on the isolation level set in the current environment to be consistent.
9.1 Types of Spring transactions
Spring supports both programmatic and declarative transaction management:
- Programmatic transaction
Programmatic transaction management uses TransactionTemplate.
- Declarative transaction
Declarative transaction management is based on AOP. Its essence is through the AOP function, before and after the method of interception, the function of transaction processing woven into the interception method, that is, in the target method before the start of a transaction, after the execution of the target method according to the execution of the submission or rollback of the transaction.
The advantage is that there is no need to mix transaction management code with the business logic code. Instead, transaction rules can be applied to the business logic using a transaction rule declaration in a configuration file or via the @Transactional annotation. The only downside is that the maximum granularity applies only at the method level, not at the code block level like programmatic transactions.
9.2 Spring transaction propagation mechanism
The propagation mechanism for Spring transactions describes how Spring handles the behavior of multiple transactions when they exist at the same time. The transaction propagation mechanism is actually implemented using a simple ThreadLocal, so if a method is called in a new thread, transaction propagation is effectively invalidated.
- To create a new transaction if there is no transaction, to join a transaction if there is one already in existence. This is the most common choice and the default mode. It works in most cases.
- Propagation_supports: Supports the current transaction. If there is no current transaction, execute as a non-transactional method.
- Propagation_mandatory: Use the current transaction, or throw an exception if there is no current transaction.
- Propagation_required_new: Create a transaction, and suspend the current transaction, if one exists.
- Propagation_not_supported: Executes an operation in a non-transactional manner, and suspends the current transaction, if one exists.
- Propagation_never: Executes an operation in a non-transactional manner, throws an exception if the current transaction exists.
- Propagation_nested: Executes within a nested transaction if a transaction currently exists. If there are no transactions currently, an operation similar to PROPAGation_REQUIRED is performed
9.3 Spring transaction Isolation Level
The TransactionDefinition interface defines five constants that represent the isolation level of MySQL.
- ISOLATION_DEFAULT: Use the default isolation boundary of the backend database, MySQL defaults to repeatable reads and Oracle defaults to committed reads.
- ISOLATION_READ_UNCOMMITTED: Read is not committed.
- ISOLATION_READ_COMMITTED: Read committed.
- ISOLATION_REPEATABLE_READ: repeatable read.
- ISOLATION_SERIALIZABLE: serialization.
10. Spring MVC
10.1 What is MVC?
In MVC mode, M refers to the business Model, V refers to the user interface, and C refers to the Controller. The purpose of using MVC is to separate the implementation codes of M and V. Generally, application programs are divided into Controller, Model, and View layers in development. The Model is called to generate business data, which is passed to the View, which ultimately presents the front-end results.
Spring MVC is the encapsulation of the above process, shielding a lot of low-level code and opening the outbound interface, so that developers can more easily and conveniently complete Web development based on MVC pattern.
10.2 Relationship between Spring and Spring MVC
In the beginning, there was only Spring, which only provided IOC and AOP core functions. Later, there was a mess of MVC, Security, Boot and so on. Spring is now Spring Core, and MVC stands for the MVC framework of the Web.
Spring MVC is an MVC framework, which belongs to Spring to a large extent. Spring MVC is a WEB development framework similar to Struts MVC mode. Spring MVC is a WEB framework added based on Spring functions. The relationship between Spring and SpringMVC can be understood as a parent-child container. To use SpringMVC, you must first rely on Spring.
Spring MVC is the control layer that receives the foreground value, calls the Service layer and persistence layer, and returns the data back to the foreground via Spring MVC
10.3 Core components of Spring MVC
DispatcherServlet: front controller, is the core of the whole process control, controls the execution of other components, unified scheduling, reduce the coupling between components, equivalent to the commander in chief.
Handler: Processor that performs specific business logic, equivalent to servlets or actions.
HandlerMapping: After receiving requests, the DispatcherServlet uses HandlerMapping to map different requests to different handlers.
HandlerInterceptor: Processor interceptor, an interface that you can implement if you need to do some intercepting.
HandlerExecutionChain: A processor execution chain consisting of two parts: Handler and HandlerInterceptor. (The system has a default HandlerInterceptor, but you can add an interceptor if you need an additional interceptor.)
HandlerAdapter: Before the Handler executes a business method, it needs to perform a series of operations, including form data validation, data type conversion, form data encapsulation into a JavaBean, etc. All these operations are completed by HandlerApater. Developers only need to focus on the processing of business logic. The DispatcherServlet executes different handlers through the HandlerAdapter.
ModelAndView: Loads model data and view information, which is returned to the DispatcherServlet as a result of Handler processing.
ViewResolver: a view parser that DispatcheServlet uses to parse a logical view into a physical view and render the result back to the client.
10.4 Spring MVC Workflow
The DispatcherServlet represents the front controller and is the control center for the entire SpringMVC. The user makes a request, receives it, and intercepts it.
HandlerMapping maps processors. The DispatcherServlet invokes HandlerMapping, which looks up the Handler based on the requested URL.
HandlerExecution refers to a specific Handler that looks for a controller based on a URL, such as Hello.
HandlerExecution passes parsed information to the DispatcherServlet, such as parsed controller mappings.
HandlerAdapter represents a processor adapter that executes handlers according to specific rules.
Handler lets specific controllers execute.
The Controller returns specific execution information to the HandlerAdapter, such as ModelAndView.
HandlerAdapte R passes the view logical name or model to the DispatcherServlet.
The DispatcherServlet calls the ViewResolver to resolve the logical view name passed by the HandlerAdapter.
The view parser passes the parsed logical view name to the DispatcherServlet.
The DispatcherServlet invokes specific views based on the view results parsed by the view parser.
The final view is presented to the user.
Although the overall process of Spring MVC is complex, it is very simple in actual development. Most components do not need to be created and managed by developers, but only need to be configured through configuration files. Only Handler, View and Modle really need to be processed by developers.
However, with the development of front and back end separation and microservices, the development model is not used much, most of the cases are SpringBoot + Vue.
11. Spring Boot
11.1 Introduction to Spring Boot
Spring Boot is developed based on Spring. Spirng Boot itself does not provide the core features and extension functions of Spring framework, but is only used to develop a new generation of applications based on Spring framework quickly and agile. It is not intended as a solution to replace Spring, but rather as a tool that works closely with the Spring framework to enhance the Spring developer experience. Spring Boot works with the core idea of convention over configuration, and has the following advantages compared with Spring:
Spring Boot allows you to build standalone Spring applications.
Spring Boot has built-in containers like Tomcat, Jetty, and Undertow, which means you can run them without having to deploy them.
Spring Boot eliminates the tedious configuration of XML files that Spring does.
Spring Boot can automatically configure (core)Spring. SpringBoot changes the XML configuration to Java, changes bean injection to annotation injection (@autowire), and condenses multiple XML and properties configurations into a appliaction.yml configuration file.
Spring Boot provides some of the existing functionality, such as metrics tools, form data validation, and some third-party functionality for external configuration.
Spring Boot integrates common dependencies (development libraries such as Spring-WebMVC, Jackson-JSON, Validation-API, and Tomcat) and provides POM to simplify Maven configuration. When we introduce core dependencies, SpringBoot will introduce other dependencies.
11.2 SpringBoot Precautions
- SpringBoot pulling away
All functional scenarios are extracted to form a starter. Spring-boot-starter-xxx is the scenario initiator of spring-boot. All you need to do is introduce these starters into your project, and all related dependencies are imported.
- Principle of Automatic configuration
SpringBoot gets the value specified by EnableAutoConfiguration from the META-INF/ Spring. factories in the classpath at startup
Let’s see if the functionality we need is in the automatic configuration class xxxxAutoConfigurartion written by default in SpringBoot.
Let’s take a look at what components are configured in this auto-configuration class; (As long as the component we want to use exists in it, we don’t need to manually configure it.)
When you add a component to the auto-configuration class in the container, you get some properties from the xxxxProperties class. We just need to specify the values for these properties in the configuration file.
- Integration of various components
For example, MyBatis, Redis, Swagger, Security, Shrio, Druid, etc.
11.3 Springboot Basic startup principles
The SpringApplication class does four things:
Determine whether the type of application is a normal project or a Web project
Find and load all available initializers into the Initializers property
Find all application listeners and set them to the Listeners properties
Infer and set the definition class of the main method to find the running main class
The SpringBoot startup process is as follows:
11.3 Architecture Evolution
- Single application
Traditional projects put all business functions in one project. This single architecture structure is relatively simple and practical for small projects. However, as the volume of services increases, the logic becomes more and more complex, and the project gradually becomes huge and the logic becomes confused, causing great difficulties to maintenance and development.
- Vertical architecture
The original large individual projects were divided into several small individual projects according to business logic. For example, the logistics system and customer relationship system were separated from the original electronic mall system and constructed into two small projects. Although this architecture solves the problem that the original single project is too large, it also brings the problems of data redundancy and coupling.
- SOA architecture
Service Oriented Architecture (SOA), which is based on the vertical Architecture, extracts the common components in the original project to form services, providing services for each system. The service layer is the extracted common components. Small systems at the system layer complete their business logic by invoking services through the ESB Enterprise Service Bus (ESB), which acts as a communication bridge between projects and services, as well as WebServices. However, the granularity of SOA architecture extraction is relatively rough, the coupling between system and service is very large, and the boundary between system and service is not clear, causing certain difficulties for development and maintenance.
- Microservices Architecture
Microservices architecture has a smaller granularity of service extraction, completely isolating the service layer in the system. Following a single principle, the boundaries between the system layer and the service layer are clear, and each system invokes the required microservices through the service gateway. Microservices are transmitted between each other over lightweight protocols such as RESTful, which is lighter than an ESB. However, the development cost of this architecture is relatively high (because of the newly added requirements of fault tolerance and distributed transactions), and the requirements on the team are relatively large, so it is not suitable for small projects and teams.
- Framework evolution
Powerful configuration capabilities are an advantage when a canonical framework is derived from a complex application scenario and users only need to perform various configurations rather than implement them themselves. After development to a certain extent, people select practical functions and design essence according to the actual production and application situation, and reconstruct some lightweight frameworks. Later, in order to improve the development efficiency, the original various configurations are too troublesome, so began to advocate the scheme that the convention is greater than the configuration, and derived some one-stop solutions.
12. Spring Cloud
Definition of microservices:
A new form of architecture was proposed by Martin Fowler in 2014. Microservices architecture is an architectural pattern that advocates the partitioning of a single application into a set of small services that coordinate with each other to provide ultimate value to users. Each service operation in the process of its independence, using lightweight communication mechanism between service and the service (such as HTTP or Dubbo) collaboration with each other, each of these services are built around the specific business, and can be independently deployed to a production environment, in addition, should try to avoid a unified, centralized service management mechanism, for a specific service, Choose the appropriate language and tool (such as Maven) to build it based on the business context.
The core of the micro service is the application of the “one-stop” work style of traditional, according to the business into a service, a coupling, thoroughly to each service function of a single business service, a service to do one thing, from a technical point of view is a small, independent processing, the concept of the similar process, can start alone or destroyed by oneself, have their own independent of the database.
Core problems in the era of micro services (fundamental problem: unreliable network) :
There are many services, how to access the client, how to provide an external gateway?
With so many services, how do they communicate with each other? The HTTP or RPC?
So many services, how to govern? Registration and discovery of services.
What if the service is down? Circuit breaker mechanism.
Mainstream microservice frameworks:
Spring Cloud Netflix
Spring Cloud Alibaba
Spring + Dubbo + ZooKeeper
SpringCloud Netflix has been written about in detail and will not be repeated here.
13. Common notes
I don’t know why, maybe it’s because I don’t use it very much. Finally, a few simple notes to end. There are Spring core annotations, SpringBoot annotations, SpringCloud annotations, task execution and scheduling annotations, testing annotations, JPA annotations, SpringMVC and REST annotations, and so on. Here are just a few core annotations. Kylin bug, get a detailed Java interview questions manual, covering 25 core technical points, welcome to exchange, like the article remember to pay attention to me like yo, thank you for your support!
Component: CommandLineRunner can be configured to be used when a Component does not belong to one of the following classes. @Controller, @Service, and @Repository are Component refinments.
@autoWired: automatically import dependent beans, default byType, complete property, method assembly, can annotate class member variables, methods, constructors, add (required=false) not found and no error
@import: Similar to @bean, more flexible to Import other configuration classes. ImportSelector, ImportBeanDefinitionRegistrar, etc
@bean: a Bean configured in the equivalent XML, used in a method to generate a Bean and hand it over to Spring to manage
@value: specifies a default Value for fields, constructor arguments, and method arguments. Supports #{} and ${}. The value of the application.properties configuration in SpringbBoot is typically assigned to the variable.
@Configuration: Equivalent to Spring’s XML Configuration file, using Java code to check type safety. If you sometimes have to use an XML Configuration file, you can use the @Configuration class as the main Configuration class for your project and load the XML file using the @ImportResource annotation
@Qualifier: This annotation is usually used in conjunction with @AutoWired. It can be used when you want more control over the injection process, such as when Spring cannot choose between more than two beans of the same type