Java interview must-test points - Lecture 07 (Part 1): Must-know framework - Spring Family Bucket

This class mainly introduces the commonly used application frameworks in Java, focusing on the following three parts.

  1. The main knowledge points in the Spring framework;

  2. NIO framework Netty and mainstream RPC frameworks Motan, Dubbo and gRPC based on Netty;

  3. ORM framework MyBatis.

Summary of commonly used frameworks

Let’s first look at the summary of knowledge points of commonly used frameworks, as shown in the figure below.

As shown in the picture above, the upper left is the Spring series. Many developers regard Spring as the best Java project in their minds, bar none. The Spring series contains a lot of projects that can meet all aspects of Java development. Let’s take a look at some commonly used Spring frameworks.

Spring

Spring Framework, which is what we often call Spring Framework, includes IoC dependency injection, Context context, Bean management, SpringMVC and many other functional modules. Other Spring projects such as Spring Boot will also rely on the Spring Framework.

The goal of Spring Boot is to simplify the creation, development and deployment of Spring applications and services. It simplifies configuration files, uses an embedded web server, and contains many out-of-the-box microservice functions that can be deployed jointly with Spring Cloud. The core idea of ​​Spring Boot is that convention is greater than configuration, and applications only require very little configuration, simplifying the application development model.

Spring Data is a data access and operation toolset that encapsulates the operation capabilities of multiple data sources, including: JDBC, Redis, MongoDB, etc.

Spring Cloud is a complete microservice solution and a collection of microservice frameworks with different functions. 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. For example, sleuth provides full-link tracking capabilities, and the Netflix suite provides many governance components such as hystrix fuses and zuul gateways. The config component provides dynamic configuration capabilities, and the bus component supports the use of message queues such as RabbitMQ, Kafka, and ActiveMQ to implement event communication between distributed services.

Spring Security is 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. Here you can learn about the OAuth2 authorization mechanism and JWT authentication method. OAuth2 is an authorization mechanism that provides a complete authorization and authentication process. The full name of JWT is JSON Web Token, which is an authentication implementation that includes authentication information in the token. JWT can be used as a specific implementation method of authentication in the OAuth2 authorization mechanism.

Struts

Struts is the control layer in the once very popular Web combination SSH. We know that Web services are generally built using the MVC layered 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 returning the view displayed to the user. What Struts implements is the role of the control layer.

Struts uses Filter implementation to intercept classes and create an Action for each request. However, the SSH combination using Struts has gradually been replaced by the SSM combination using SpringMVC, that is, the combination of SpringMVC+Spring+MyBatis. On the one hand, the reason is that Struts' handling of several security vulnerabilities has affected everyone's confidence in Struts; On the one hand, SpringMVC is more flexible, does not require additional configuration, does not have problems such as integration with Spring, and is more convenient to use. Therefore, it is recommended to focus on learning the SSM framework.

ORM

ORM is object-relational matching, which solves the mismatch problem between object-oriented and relational databases. Simply put, it is to convert data in a relational database into objects in an object-oriented program. Commonly used ORM frameworks include Hibernate and MyBatis, which are the H and M in SSH combination and SSM combination.

Let's take a look at the features and differences between Hibernate and MyBatis.

  • Hibernate provides a complete encapsulation of the database structure, realizes the mapping between POJO objects and database tables, and can automatically generate and execute SQL statements. As long as the mapping relationship between POJO and database tables is defined, database operations can be completed through the methods provided by Hibernate. Hibernate complies with the JPA specification, which is the Java persistence layer API.

  • MyBatis maps the parameters required by SQL and the returned result fields to specified objects through mapping configuration files. MyBatis does not automatically generate SQL and requires you to define SQL statements yourself, but it is more convenient to optimize SQL statements.

To sum up, Hibernate configuration is much more complicated than MyBatis, and the learning cost is also higher than MyBatis. MyBatis is simple, efficient, and flexible, but you need to maintain SQL yourself; Hibernate is powerful, fully automatic, and adapts to different databases, but it is very complex and has less flexibility.

Netty is a high-performance asynchronous event-driven network communication framework. Netty encapsulates JDK's native NIO, simplifying the development of network services.

In addition, similar frameworks include MINA and Grizzly, but they are currently used relatively rarely and generally do not appear in interview questions. They can be simply understood as a matter of interest.

RPC

RPC services, Motan, Dubbo, and gRPC are all commonly used high-performance RPC frameworks that can provide complete service management capabilities. The communication layer of the Java version is based on the Netty implementation mentioned above.

other

In addition, Jersy and RESTEasy are both frameworks that can quickly develop RESTful services. Compared with SpringMVC, these two frameworks are based on the JAX-RS standard, while SpringMVC is based on Servlet and uses its own built API, which are two different standards.

The Shiro framework is an open source permission management framework similar to Spring Security, used for access authorization, authentication, encryption and session management. Can support stand-alone and distributed session management. Compared with Security, Shiro is simpler and easier to use.

Detailed explanation of Spring framework

For the Spring framework, the processes and implementations involved in the explanation are based on the latest 5.x version by default. Let’s first look at some important concepts in Spring.

IoC

IoC, that is, inversion of control, as shown below, takes a company recruitment position as an example. Suppose a company has product, R&D, testing, etc. positions. If the company arranges candidates one by one according to job requirements, as shown by the downward arrow in the picture, this is a forward process. If the reverse is true, instead of the company arranging candidates, a third-party headhunter will match positions and candidates and then make recommendations, as shown by the upward arrow in the picture, this is an inversion of control.

In Spring, the properties of an object are created by the object itself, which is a forward process; if the properties are not created by the object, but are automatically assembled by Spring, it is an inversion of control. DI here is dependency injection, which is the way to achieve inversion of control. The forward process leads to high coupling between objects. IoC can solve the problem of object coupling, facilitate the reuse of functions, and make the program structure very flexible.

Context and Beans

Spring uses two concepts when implementing IoC: Context and Bean. As shown in the figure below, all objects managed by Spring and created by Spring for dependency injection are called a Bean. After Spring creates and completes dependency injection, all beans are managed in a context called Context.

AOP

AOP stands for aspect-oriented programming. As shown in the figure below, generally our program execution process is to call the Service layer from the Controller layer, then the Service layer calls the DAO layer to access data, and finally returns the results layer by layer. This is the vertical processing in the order of program execution as shown by the downward arrow in the figure.

However, let’s think about this problem. There will be multiple different services in a system, such as user services, product information services, etc. The Controller layer of each service needs to verify parameters and handle exceptions. If you follow the red color in the figure, part, cross-cut the vertical processing processes of different services, and complete common functions in each aspect, such as identity authentication, verification parameters, exception handling, etc., so that there is no need to write the same logic in each service , This is the problem solved by AOP thinking. AOP is divided by function, cross-cutting different positions in the service sequence execution process, and completing the functions that each service needs to implement.

components

Let’s look at the Spring framework again. The following figure lists the main components of the Spring framework. This picture comes from the Spring4.x documentation. The Portlet component on the right in the latest 5.x version has been abandoned, and the WebFlux component for asynchronous reactive processing has been added. There is no need to know all the components in detail here. You only need to focus on the implementation of the most commonly used components and know what type of function each component is used to implement.

The red boxes in the picture are the more important components. The Core component is the core of all Spring components; the Bean component and the Context component I just mentioned are the basis for implementing IoC and dependency injection; AOP components are used to implement aspect-oriented programming; Web Components include SpringMVC, which is the control layer implementation of Web services.

Dynamic proxy and static proxy

Next are the knowledge points related to mechanisms and concepts in Spring, as shown in the figure below.

AOP is implemented through the proxy mode, which executes the inserted aspect logic when a method of the object is called. The implementation methods include dynamic proxies, also called runtime enhancement, such as JDK proxies and CGLIB; static proxies are woven in at compile time or during class loading, such as AspectJ. Regarding AOP, you also need to know the corresponding annotations and specific usage methods such as aspect, pointcut, and advice.

PlaceHolder dynamic replacement

Dynamic replacement of PlaceHolder mainly requires understanding the time when the replacement occurs. It is implemented through the BeanFactoryPostProcessor interface after the Bean Definition is created and before the Bean is initialized. The main implementation methods are PropertyPlaceholderConfigurer and PropertySourcesPlaceholderConfigurer. The implementation logic of these two classes is different. Spring Boot uses PropertySourcesPlaceholderConfigurer to implement it.

affairs

For transactions, you need to understand the isolation type and transaction propagation type specified for transactions in Spring. Here you need to know that the isolation level of a transaction is implemented by a specific database, which will be introduced in detail in the database section. Regarding transaction propagation types, you can focus on the most commonly used REQUIRED and SUPPORTS types.

Core interface/class

Let’s look at the core classes that need to be mastered in the upper right corner of the picture.

  • ApplicationContext saves the entire application context of IoC, and any Bean can be obtained through the BeanFactory;

  • The main function of BeanFactory is to create specific beans based on Bean Definition;

  • BeanWrapper is a wrapper for Beans. It is generally used within Spring IoC. It provides functions such as accessing Bean attribute values, attribute editor registration, type conversion, etc., making it convenient for IoC containers to access Bean attributes in a unified way;

  • FactoryBean returns the actual Bean object through the getObject method. For example, the dynamic proxy of the referer to the service in the Motan framework is implemented through FactoryBean.

Scope

The Scope of a Bean refers to the scope of the Bean. By default, it is the singleton mode, which is also the most commonly used method; the multi-case mode, that is, a new Bean will be created every time a Bean is obtained from the BeanFactory. Request, Session, and Global-session are Scopes used in Web services.

  • Request creates an instance for each request;

  • Session guarantees only one instance within a session cycle;

  • Global-session is no longer used in version 5.x, and two scopes, Application and Websocket, have been added to ensure that only one instance is created in a ServletContext and a WebSocket respectively.

You can also learn about Spring's event mechanism, the five standard events defined by Spring, and how to customize events and implement the corresponding ApplicationListener to handle custom events.

application

Let’s look at the knowledge points related to Spring applications, as shown in the figure below.

First of all, you must master the use of commonly used annotations.

  1. Type class annotations, including Controller, Service, etc., you can focus on the difference between Component and Bean annotations:

    1. The @Component annotation is used on a class to indicate that this class is a component class and requires Spring to create a Bean for this class.
    2. The @Bean annotation is used on a method to tell Spring that this method will return a Bean object, and the returned object needs to be registered in Spring's application context.
  2. When setting class annotations, you can focus on understanding different automatic assembly mechanisms such as @Autowire and @Qualifier, as well as byType and byName.

  3. The Web class is mainly focused on understanding, paying attention to path matching annotations such as @RequestMapping, @GetMapping, @PostMapping, and parameter acquisition annotations such as @PathVariable and @RequestParam.

  4. Functional class annotations, including @ImportResource reference configuration, @ComponentScan annotation automatic scanning, @Transactional transaction annotation, etc., will not be introduced one by one here.

As shown on the right side of the figure above, in the Spring application part, you also need to understand several ways to configure Spring: XML file configuration, annotation configuration, and configuration using API.

The automatic assembly mechanism requires understanding of the four main methods: automatic assembly by type matching, automatic assembly by bean name, automatic assembly and automatic detection in the constructor.

Finally, you can also learn about the configuration methods of collection class properties such as List, Set, and Map and the use of internal beans.

Context initialization process

As shown in the figure below, there are three types of Context on the left:

  • Context in XML configuration mode;

  • Spring Boot 的 Context;

  • The context of the web service.

No matter what kind of Context, the refresh method of the AbstractApplicationContext class will be called after creation. The process is as follows.

  1. First, prepare for the refresh, including setting the start time, setting the activation state, and initializing the placeholders in the Context environment. This action is performed by the subclass according to the needs of the subclass, and then it is verified whether the necessary properties are missing.

  2. Refresh and get the internal Bean Factory.

  3. Prepare the BeanFactory, such as setting up class loaders and post-processors, configuring types that are not automatically assembled, and registering default environment beans.

  4. Provides post-processing BeanFactory extension capabilities for Context subclasses. If the subclass wants to do some special logic after the Bean definition is loaded and before starting to initialize the context, it can override this method.

  5. Execute the Bean Factory suffix processor registered in the Context. There are two post-processors, one is a post-processor that can register Bean, and the other is a post-processor that processes BeanFactory. The order of execution is that the processors that can register Bean are executed first according to priority, and then the processors for BeanFactory are executed according to priority. For Spring Boot, this step will parse the annotated Bean Definition. The process is shown on the right side of the figure, triggered by ConfigurationClassPostProcessor, parsed by ClassPathBeanDefinitionScanner and registered to BeanFactory.

  6. Register the Bean's postfix processor in the BeanFactory in order of priority. The Bean postprocessor can perform processing before and after the Bean is initialized.

  7. Initialize the message source, which is used to support the internationalization of messages.

  8. Initialize the application event broadcaster. The event broadcaster is used to notify ApplicationListener of events generated by various applications. It is a standard observer pattern.

  9. Is an extension step left to subclasses to allow a specific Context subclass to initialize other beans.

  10. Register the Bean that implements ApplicationListener to the event broadcaster and notify the broadcaster of early unbroadcast events.

  11. Freeze all modifications to bean description information and instantiate non-lazy-loaded singleton beans.

  12. Complete the context refresh work, call the onFresh() method of LifecycleProcessor and publish the ContextRefreshedEvent event.

  13. In finally, perform step 13 to reset public caches, such as caches in ReflectionUtils, caches in AnnotationUtils, etc.;

At this point, Spring's Context initialization is completed. Due to space and time constraints, the most important main process is introduced here. It is recommended to read the source code after class to review this knowledge point and complete the details.

Bean life cycle

The life cycle of Bean is often asked in interviews. As shown in the figure below, let's first look at the green part, the creation process of Bean.

  1. Call the Bean's constructor to create the Bean;

  2. Call the setter method through reflection to perform dependency injection of properties;

  3. If the BeanNameAware interface is implemented, the name of the Bean will be set;

  4. If BeanFactoryAware is implemented, BeanFactory will be set to the Bean;

  5. If ApplicationContextAware is implemented, ApplicationContext will be set for the Bean;

  6. If the BeanPostProcessor interface is implemented, the preprocessing method is executed;

  7. If the InitializingBean interface is implemented, execute the afterPropertiesSet method;

  8. Execute custom init method;

  9. Execute the post-processing method of the BeanPostProcessor interface.

The above completes the Bean creation process. When the Bean needs to be destroyed after use, the destroy method of the DisposableBean interface will be executed first, and then the custom destroy method will be executed. It is also recommended to read the source code to deepen your understanding of this part.

Extension ports

When extending Spring's customized functions, you can choose some extension points, as shown in the figure below.

  • BeanFactoryPostProcessor is a BeanFactory post-processor that supports some additional processing of BeanFactory after the standard initialization of BeanFactory is completed. As mentioned when talking about the Context initialization process, at this time all the Bean description information has been loaded, but the Bean has not been initialized yet. For example, the PropertyPlaceholderConfigurer mentioned earlier replaces placeholders in Bean properties at this extension point.

  • BeanDefinitionRegistryPostProcessor, which extends from BeanFactoryPostProcessor, provides the ability to add Bean Definition before executing the functions of BeanFactoryPostProcessor, allowing additional beans to be registered before initializing general beans. For example, you can create a new proxy Bean based on the Bean's Scope here.

  • BeanPostProcessor, provides the ability to insert custom logic before and after Bean initialization. The difference between BeanFactoryPostProcessor and BeanFactoryPostProcessor is that the objects processed are different. BeanFactoryPostProcessor processes BeanFactory, and BeanPostProcessor processes Bean.

The above three extension points can specify the execution order by implementing the Ordered and PriorityOrdered interfaces. Processors that implement the PriorityOrdered interface will be executed before those that implement the Ordered interface.

  • ApplicationContextAware can obtain the ApplicationContext and the beans in it. When you need to dynamically obtain the beans in the code, you can implement this interface.

  • InitializingBean can execute specific logic after the Bean initialization is completed and all properties are set, such as verifying properties for automatic assembly, etc.

  • DisposableBean is used to perform specific logic before the Bean is destroyed, such as doing some recycling work.

  • ApplicationListener is used to listen to Spring's standard application events or custom events.

Spring Boot

Let’s look at the knowledge points related to Spring Boot, as shown in the figure below.

The first is the main steps of the Spring Boot startup process:

  1. To configure Environment.

  2. Prepare the Context context, including performing post-processing of the ApplicationContext, initializing the Initializer, and notifying the Listener to handle the ContextPrepared and ContextLoaded events.

  3. Execute refreshContext, which is the refresh method of the AbstractApplicationContext class introduced earlier.

Then you need to know that there are two contexts in Spring Boot, one is bootstrap and the other is application. Among them, bootstrap is the parent context of the application and will be loaded before applicationn. Bootstrap is mainly used to load configuration information from additional resources and can also decrypt properties in local external configuration files. Properties in bootstrap will be loaded first and cannot be overridden by the same local configuration by default.

Let’s look at Spring Boot’s annotations.

You need to know that @SpringBootApplication contains three annotations: @ComponentScan, @EnableAutoConfiguration, and @SpringBootConfiguration, and the @SpringBootConfiguration annotation contains the @Configuration annotation. That is the automatic configuration function of Spring Boot. The @Conditional annotation is an annotation that controls the effective conditions of automatic configuration, such as configuring when a Bean or Class exists or does not exist, configuring when the conditions are met, etc.

Finally, let’s take a look at several special modules of Spring Boot.

  • Starter is a way of seamlessly integrating functions provided by Spring Boot. When using a certain function, developers do not need to pay attention to the processing of various dependent libraries, and no specific configuration information is required. Spring Boot automatically configures Bean creation. For example, when you need to use the Web function, you only need to introduce Spring-boot-starter-web in the dependency.

  • Actuator is used to monitor and manage applications, and supervises, audits, and collects the running status of applications through RESTful API requests.

  • DevTools provides support for a series of development tools to improve development efficiency. For example, hot deployment capabilities, etc.

  • CLI is the command line interface. It is a command line tool that supports the use of Groovy scripts and can quickly build Spring prototype projects.

Guess you like

Origin blog.csdn.net/g_z_q_/article/details/129894332