The Spring framework has been favored by developers since its inception, and some people affectionately call it the Spring Family bucket. It includes SpringMVC, SpringBoot, Spring Cloud, Spring Cloud Dataflow and other solutions.

Many developers regard Spring as the best Java project they have ever had.

So this is the key is also difficult, must be able to work, interview affirmation test.

So, take 10 minutes today to review the Spring framework.

Spring knowledge – summary


The Spring family contains a large number of projects that cater to all aspects of Java development.

First, take a look at the summary of knowledge points of commonly used frameworks, as shown in the figure:

ⅰ. Five commonly used Spring frameworks


1.spring framework

The spring framework includes ioc dependency injection, Context Context, bean management, SpringMVC and many other functional modules. Other Spring projects, such as Spring Boot, also rely on the Spring framework.

2.spring boot

It aims to simplify the creation, development, and deployment of Spring applications and services, simplifies configuration files, uses an embedded Web server, and includes many out-of-the-box microservices capabilities that can be deployed in conjunction with Spring Cloud.

The core idea of Spring Boot is that convention is greater than configuration, and applications need only a little configuration, simplifying the application development mode.

3.Spring Data

Is a data access and operation tool set, encapsulating the operation capability of a variety of data sources, including: JDBC, Redis, MongoDB, etc.

4.Spring Cloud

Is a complete set of microservice solutions, is a series of different functions of the collection of microservice frameworks. Based on Spring Boot, Spring Cloud simplifies the development of distributed systems and integrates various service governance capabilities such as service discovery, configuration management, message bus, load balancing, circuit breakers, and data monitoring. Sleuth, for example, offers full-link tracking capabilities, and Netflix suite offers Hystrix fuses, Zuul gateways, and many other governance components. The Config component provides dynamic configuration capability, and the Bus component supports message queues such as RabbitMQ, Kafka and Activemq to realize event communication between distributed services.

5. Spring Security

It is mainly used to quickly build secure applications and services. Based on Spring Boot and Spring Security OAuth2, common Security models such as single sign-on, token relay and token exchange can be quickly implemented. You can learn about oAUTH2 authorization and JWT authentication. Oauth2 is an authorization mechanism that provides a complete authorization and authentication process. JWT is a JSON Web Token, which is an authentication implementation that contains authentication information in the Token. Oauth2 authorization mechanism can apply JWT as a specific authentication implementation method.

Ii. Specific functions of Struts


Struts is the control layer in SSH, the once-popular Web combination. We know that Web services are generally built with MVC hierarchical model, that is, the Model layer is responsible for the internal data model, the Controller is responsible for the distribution control of requests, and the View layer is responsible for the view returned to the user for display. Struts implements the role of the control layer.

Struts uses a Filter implementation that intercepts classes and creates an Action for each request. The SSH combination using Struts has gradually been replaced by the SSM combination using springMVC, namely the combination of Spring-MVC+Spring+MyBatis. On the one hand, because of the treatment of several security vulnerabilities by Struts, everyone’s confidence in Struts has been affected. On the other hand, SpringMVC is more flexible, does not need additional configuration, does not have problems with spring integration, and is more convenient to use, so it is recommended to learn the SSM framework.

ⅲ. Common ORM framework


ORM is object relation matching, which is to solve the problem of mismatch between object oriented and relational database. In simple terms, data in a relational database is converted into objects in an object-oriented program.

The commonly used ORM frameworks are Hibernate and MyBatis, that is, H and M in SSH combination and SSM combination.

Their characteristics and differences are as follows:

Hibernate provides a complete encapsulation of the database structure, implements the mapping between POJO objects and database tables, and automatically generates and executes SQL statements. Once you have defined the mapping between POJOs and database tables, you can perform database operations through Hibernate’s methods. Hibernate complies with the JPA specification, which is the Java Persistence layer API.

Mybatis maps parameters required by SQL and returned result fields to specified objects by mapping configuration files. Mybatis does not automatically generate SQL. You need to define SQL statements by yourself, but it is more convenient to optimize SQL statements.

To sum up:

  1. Hibernate configuration is much more complex than MyBatis and costs more to learn. Mybatis, simple, efficient, flexible, but need to maintain their own SQL;
  2. Hibernate is powerful, fully automated, and adaptable to different databases, but very complex and a little less flexible.

ⅳ. Introduction to Netty


Netty is a high-performance asynchronous event-driven network communication framework. Netty encapsulates JDK native NIO and simplifies the development of network services. More on this below

In addition, there are also mina and Grizzly frameworks of the same type, but they are rarely used at present and will not appear in interviews. They can be simply understood as an interest.

ⅴ. RPC Service


Motan, Dubbo and gRPC are commonly used high-performance RPC frameworks, which can provide perfect service governance capabilities. The Communication layer of the Java version is based on the previously mentioned Netty implementation. Their characteristics will be described later.

ⅵ. Other commonly used frameworks


Jersy and restEasy are both frameworks for developing restful services quickly.

Both frameworks are based on the jax-rs standard compared to springmvc, while springmvcs is servlet-based and uses its own built apis, which are two different standards.

Shiro framework is an open source permission management framework similar to Spring Security for access authorization, authentication, encryption, and session management. Supports single-machine and distributed session management.

Compared to Security, Shiro is much easier to use.

Spring knowledge point – detailed explanation


ⅰ. Basic Concepts of Spring


The processes and implementations covered in this article are based on the latest 5.x release by default.

Several important concepts in Spring are as follows:

1.IOC

IOC, which stands for inversion of control, as on the far left, is an example of what companies are recruiting for:

Suppose a company has product, R&D, testing, etc. If the company arranges candidates one by one according to job requirements, the downward arrow in the figure indicates a positive process. If, in reverse, a third-party headhunter matches the job with the candidate instead of the company, and then makes the recommendation, as shown by the upward arrow, this is inversion of control.

In Spring, the properties of an object are created by the object itself, which is the forward flow. If the property is not created by the object but is automatically assembled by Spring, this is inversion of control. DI, which stands for dependency injection, is the way inversion of control is implemented. The forward process leads to the high coupling between objects, IOC can solve the problem of object coupling, is conducive to the reuse of functions, can make the program structure become very flexible.

2. Context Context and bean

Spring uses two concepts for IOC implementation: context context and beans.

As the middle figure shows, all spring-managed objects created by Spring for dependency injection are called beans. After Spring creates and completes dependency injection, all beans are managed in a single context called context.

3.AOP

AOP is faceted programming. As shown in the figure on the right, the typical program execution flow is from the Controller layer to the Service layer, then the Service layer to the DAO layer to access data, and finally to return results layer by layer.

This is the vertical processing in program execution order shown by the down arrow in the figure. However, there will be multiple different services in a system, such as user service, commodity information service and so on. The Controller layer of each service needs to verify parameters and deal with exceptions. If the vertical processing process of different services is crosscut according to the red part in the figure and common functions are completed on each section, Such as authentication, validating parameters, handling exceptions, and so on, so that you don’t have to write the same logic in every service, which is the problem AOP thought solves.

AOP is divided by function, crosscutting the different positions in the service sequential execution process to complete the functions that each service needs to implement in common.

ⅱ. Spring Framework


The figure above lists the main components of the Spring framework. This image is from the documentation for Spring 4.x. In the current 5.x release, the portlet on the right has been deprecated and a WebFlux component for asynchronous responsive processing has been added.

You don’t need to know all the components in detail, just focus on the most common component implementations and know what kind of functionality each component is used to implement.

The red box is the most important component. The core component is the core of all spring components. The bean component and context component, as I mentioned earlier, are the foundation for IOC and dependency injection; AOP components are used to implement section-oriented programming; Web components including SpringMVC are control layer implementations of Web services.

Iii. Mechanism and implementation in Spring


1.AOP

AOP is implemented through a proxy pattern that performs the inserted aspect logic when invoking a method of an object. Dynamic proxies, also known as runtime enhancements, such as JDK proxies, CGLIB; Static proxies are woven at compile time or class load time, as in AspectJ.

There are also aspects, pointcut, advice, and other annotations that need to be learned about AOP and how to use them.

2. PlaceHolder dynamic replacement

The main thing to understand is when the substitution happens, after the bean Definition is created and before the bean is initialized, by implementing the BeanFactoryPostProcessor interface. Main realization way has accomplished and PropertySourcesPlaceholderConfigurer. These two classes is different implementation logic, spring the boot using PropertySourcesPlaceholderConfigurer implementation.

3. The transaction

You need to understand the isolation types and transaction propagation types specified for transactions in Spring. Keep in mind that transaction isolation levels are implemented by specific databases, which I’ll cover in more detail in the Database section.

The propagation types of transactions can be focused on the most commonly used REQUIRED and SUPPORTS types.

4. Core interface classes

  • The ApplicationContext holds the entire ApplicationContext of ioc and can be used to fetch any bean from its beanfactory.
  • The main function of BeanFactory is to create a specific bean according to the bean Definition;
  • BeanWrapper is a wrapper around beans, usually used within Spring IOC. It provides access to Bean property values, property editor registration, type conversion and other functions, so that the IOC container can access Bean properties in a unified way.
  • A FactoryBean returns the actual bean object through the getObject method. For example, the motan framework’s referer dynamic proxy for a service is implemented through FactoryBean.

5.Scope

The scope of a bean refers to the scope of the bean. By default, this is the singleton pattern, which is the most commonly used. A multi-case pattern, where a new bean is created each time a bean is retrieved from the beanFactory.

Request, Session, and global-session are scopes used in Web services. Each request creates an instance, and session ensures only one instance within a session period.

Global-session is no longer used in 5.x, and Application and Websocket are added to ensure that only one instance is created in a ServletContext and a Websocket, respectively.

6. Event mechanism

Spring’s event mechanism requires knowledge of the five standard events defined by Spring, as shown in the figure above. Learn how to customize events and implement the corresponding applicationListener to handle custom events.

ⅳ. Related to Spring applications


1. Common comments

A. Type class annotation:

Type Class annotations include controller and service

Here’s the difference between component and bean annotations:

  • Using the @Component annotation on a class indicates that the class is a Component class and requires Spring to create beans for it.
  • The @bean annotation is used on a method to tell Spring that the method will return a Bean object and that the returned object needs to be registered with Spring’s application context.

B. Set class annotations

Focus on @Autowire and @Qualifier, as well as byType and ByName.

C.w eb class notes

Pay attention to @requestMapping, @getMapping, @postMapping and other path matching annotations, and @pathvariable, @RequestParam and other parameters to obtain annotations.

D. Annotations for feature classes

These include @importResource reference configurations, @ComponentScan annotation automatic scanning, @Transactional transaction annotations, and more.

2. Configuration mode

You need to know several ways to configure Spring, XML file configuration, annotation configuration, and configuration using apis.

The autowiring mechanism requires an understanding of the four main ways of autowiring by type matching, autowiring by bean name, autowiring and autowiring in the constructor.

You also need to know how collection class attributes like List, set, map are configured and how internal beans are used.

ⅴ. Initialization process of Spring Context


In the upper left corner of the figure are three types of context, XML-configured context, SpringBoot context, and Web services context. No matter what kind of context, creating will be called to refresh AbstractApplicationContext class method, after the method that we should focus on analysis.

In the refresh method, the operation consists of 13 steps:

Step 1: Prepare for the refresh, including setting the start time, setting the activation state, initializing placeholders in the context, which are performed by subclasses depending on their needs, and then verifying that the necessary properties are missing;

Step 2: Refresh and get the internal bean Factory;

Step 3: Prepare the bean Factory, such as setting up the classloader and post-processor, configuring the non-autowiring types, and registering the default environment beans;

Step 4: Extend the ability to postprocess the bean Factory for subclasses of Context. This method can be overridden if subclasses want to do some special logic after the bean definition is loaded and before starting the context initialization.

Step 5, execute the bean Factory suffix handler registered in context;

Note: There are two types of post-handlers, one for registering bean postfixes and the other for processing bean Factories. The order of execution is that the handler for the registered bean is executed in priority first, and the handler for the BeanFactory is executed in priority.

For SpringBoot, this step resolves the annotation bean Definition. Process as shown in the right small box, triggered by ConfigurationClassPostProcessor, by ClassPathBeanDefinitionScanner analytic and register to the bean factory.

Step 6: Register bean postfix handlers in beanFactory in priority order. Bean postfix handlers can perform processing before and after bean initialization.

Step 7: Initialize the message source used to support the internationalization of the message;

Step 8: Initialize the application event broadcaster. The event announcer is used to notify applicationListener of events generated by various applications and is a standard observer mode.

Step 9: Is an extension step left to subclasses to have specific context subclasses initialize other beans;

Step 10: Register the bean implementing ApplicationListener with the event broadcaster and notify the early unbroadcast events in the broadcaster;

Step 11: Freeze all bean description modifications and instantiate non-lazy-loaded singleton beans;

Step 12: Complete the context refresh by calling the LifecycleProcessor’s onFresh() method and publishing the ContextRefreshedEvent event;

Step 13: In finally, perform step 13 to reset public caches, such as those in ReflectionUtils, AnnotationUtils, and so on;

At this point, spring’s context initialization is complete. Here only introduces the main main process, suggest reading source code after class to review this knowledge point, complete the details.

ⅵ. Bean life cycle in Spring


A bean’s life cycle is often asked in interviews, starting with the bean creation process in green:

Step 1: Create the bean by calling its constructor;

Step 2: Use reflection to call setter methods for dependency injection of properties;

Step 3: If the BeanNameAware interface is implemented, the bean name is set;

Step 4: If BeanFactoryAware is implemented, the bean Factory is set to the bean;

Step 5: If ApplicationContextAware is implemented, the bean is set ApplictionContext;

Step 6: If the BeanPostProcessor interface is implemented, perform the pre-processing method;

Step 7: After implementing the InitializingBean interface, execute the afterPropertiesSet method;

Step 8: Execute a custom init method;

Step 9: Execute the postprocessing method of the BeanPostProcessor interface.

At this point, the bean creation process is complete.

When a bean needs to be destroyed after it has been used, it first executes the Destroy method of the DisposableBean interface, and then executes the custom destroy method.

This section also suggests reading the source code for deeper understanding.

ⅶ. Spring extension interface


When extending spring’s customization capabilities, you can choose some of the following extension points:

1.BeanFactoryPostProcessor

BeanFactory is a beanFactory post-processor that supports some additional processing of the beanFactory after the beanFactory standard has been initialized. As described in the context initialization process, all bean descriptions have been loaded, but the bean has not been initialized. Mentioned above is accomplished, for example is in the extension point to replace placeholders bean properties.

2.BeanDefinitionRegistryPostProcessor

It extends BeanFactoryPostProcessor and provides the ability to add bean Definitions before performing the functions of BeanFactoryPostProcessor, allowing additional beans to be registered before general beans are initialized. For example, you can create a new proxy bean based on the scope of the bean here.

3.BeanPostProcessor

Provides the ability to insert custom logic before and after bean initialization. The difference between BeanFactoryPostProcessor and BeanFactoryPostProcessor is that they process different objects. BeanFactoryPostProcessor processes BeanFactory and BeanPostProcessor processes beans.

Note: For these three extension points, you can specify the order of execution by implementing Ordered and PriorityOrdered interfaces. The processor that implements the PriorityOrdered interface executes before the Ordered interface executes.

4.ApplicationContextAware

You can get the ApplicationContext and the beans in it, and when you need to dynamically get the beans in your code, you can do so by implementing this interface.

5.InitializingBean

Specific logic can be performed after the bean is initialized and all properties are set, such as validation of properties for autowiring, and so on.

6.DisposableBean

Used to perform specific logic, such as doing some recycling, before the bean is destroyed.

7.ApplicationListener

Used to listen for spring’s standard application events or custom events.

ⅷ, Springboot related knowledge points


1. Start the process

The main steps are to first configure the environment, then prepare the context context, This includes post-processing of the applicationContext, initializer initialization, and notification to the Listener to handle contextPrepared and contextLoaded events. Finally perform refreshContext, namely AbstractApplicationContext class refresh methods described above.

2. Configuration file

Then remember that there are two contexts in Spring Boot: bootstrap and Application.

Bootstrap is the parent context of the application, which means that bootstrap is loaded before applicaton. Bootstrap is used to load configuration information from additional resources and to decrypt properties in local external configuration files. Bootstrap attributes are loaded first and cannot be overridden by the same local configuration by default.

3. The annotation

@SpringBootApplication contains @ComponentScan, @EnableAutoConfiguration, and @SpringBootConfiguration

The @SpringBootConfiguration annotation contains the @Configuration annotation. This is the automatic configuration feature of SpringBoot.

An @Conditional annotation is an annotation that controls the conditions under which automatic configurations take effect, such as when beans or classes exist, when they do not exist, when conditions are met, and so on.

4. Featured modules

  • Starter is a way to provide seamless integration of functions provided by SpringBoot. When using a function, developers do not need to pay attention to the processing of various dependent libraries and do not need specific configuration information. Spring Boot automatically configits beans. For example, to use the Web function, you only need to add spring-boot-starter-web to the dependency.
  • The Actuator monitors and manages applications and uses restful API requests to monitor, audit, and collect applications.
  • Devtools provides support for a range of development tools to improve development efficiency. For example, hot deployment capability.
  • The CLI is a command line interface, a command line tool that allows you to quickly build Spring prototyping projects using Groovy scripts.

The above is the content that the Spring framework needs to master. It is recommended to read the source code for a deeper understanding of the core mechanism and core process mentioned above.

Reader benefits:

Share free learning materials

For Java programmers, I prepare free Java architecture learning materials (including high availability, high concurrency, high performance and distribution, Jvm performance tuning, MyBatis, Netty, Redis, Kafka, Mysql, Zookeeper, Tomcat, Docker, Dubbo, Nginx multiple knowledge architecture material etc.)

The reason why someone is always better than you is because they are already better and are constantly trying to become better, while you are still satisfied with the status quo and secretly happy! I hope you can give me a thumbs-up and follow me, and I will update the technical dry goods in the future. Thank you for your support!

How to receive information: Join the Java Technology Exchange Group963944895.Click to join the group chat, private message administrator can get free

How to improve code quality? — Summary of r&d experience from Ali P8 architects

Ali P8 shares the learning path of Java architects, the sixth point is particularly important

Eight tools every Java Developer should know

Want to interview a Java architect? Do you know the basics?

Draw a map to your core competency, turning midlife crisis into a gas station

There’s no midlife crisis, but setting goals as a plan

Being laid off is not the focus of winter, the focus is how to break the career bottleneck