Today’s sharing started, please give us more advice ~

This section summarizes the interview questions related to the SSM framework

1. What are stateful and stateless logins?

– Stateful login:

When the client requests the server for the first time (login request), the server creates a Session, saves the login user identity information into the Session, and responds to the client with the user identity information as the “door card”, and the client saves the server response “door card” information in the local Cookie.

When the client requests the server again the next time, it directly brings the “door card” stored in the Cookie of the client to the server, and the server compares the data from the Session with the “door card” to judge whether it can be used together.

  • Disadvantages of stateless login:

The server saves a large number of user ids, increasing the pressure on the server.

Client requests depend on the server, and multiple requests must access the same server (in the case of a cluster, it is equivalent to starting multiple Tomcatas, and Session data cannot be directly shared among multiple Tomcatas).

– Stateless login:

The server does not save any client user login information!

Each time a client requests, the server must have its own identity information identifier (JWT), by which the server identifies the client’s identity.

  • Benefits of stateless login:

Client requests do not depend on information from the server, and any multiple requests do not have to go to the same server.

Reduce the storage pressure on the server.

How to implement stateless login?

As shown in the figure:

  • When the client first requests the service, the server authenticates the user’s information (login).

  • If the authentication succeeds, the user identity information (excluding the password) is encrypted to form a token, which is returned to the client as a login certificate.

  • After each request, the client carries the authenticated token.

  • The service decrypts the token to determine whether it is valid.

Filters, interceptors, Aop differences?

Filters and interceptors both embody the programming philosophy of AOP and can implement functions such as logging and login authentication, but there are many differences between them.

1. Different implementation principles

The underlying implementation of filters and interceptors is quite different, with filters based on function callbacks and interceptors based on Java’s reflection mechanism (dynamic proxies).

2. Different scope of use

We see that the Filter implements the Javax.servlet.filter interface, which is defined in the Servlet specification, meaning that the use of the Filter Filter depends on containers such as Tomcat, making it available only in Web applications.

The Interceptor is a Spring component and managed by the Spring container. It does not depend on Tomcat and other containers. It can be used independently. Not only can be applied in web programs, but also can be used in Application, Swing and other programs.

3. Different trigger times

The Filter is preprocessed after the request enters the container, but before it enters the servlet, and the request ends after the servlet has finished processing it.

The Interceptor preprocesses the request after it enters the servlet, but before it enters the Controller, where it renders the corresponding view.

4. The scope of intercepted requests is different

5. Injection beans are different

In real business scenarios, applying filters or interceptors will inevitably introduce some services to process business logic.

6. Control execution sequence is different

In real development, multiple filters or interceptors may exist at the same time, but there are times when we want one filter or interceptor to be executed first, and the order in which they are executed is involved.

3. What is SpringMvc? What are its core components?

① Front-end controller (DispatcherServlet) : mainly used to receive HTTP requests and response results sent by clients to clients.

② HandlerMapping: Locate the corresponding Handler according to the requested URL.

③ Processor adapter (HandlerAdapter) : in the preparation of the processor (Handler) should be in accordance with the rules of the processor adapter (HandlerAdapter) requirements to write, through the adapter can correctly execute the Handler.

(4) Handler: is the Controller layer code we often write, such as: UserController.

⑤ View resolver (ViewResolver) : parse the View and return the ModelAndView object into a real View object to the front-end controller.

⑥ View: A View is an interface whose implementation classes support different View types (JSP, FreeMarker, Thymleaf, etc.).

4. Springmvc execution process?

① First, the user sends an HTTP request to the SpringMVC front-end controller DispatcherServlet.

② After receiving the request, the DispatcherServlet invokes the HandlerMapping processor mapper, locates the specific processor Handler according to the request URL, and returns the Handler object to the DispatcherServlet.

③ Next, the DispatcherServlet calls the HandlerAdapter processor adapter, which calls the corresponding Handler Handler to process the request and returns a ModelAndView object to the forward controller.

④ The DispatcherServlet then hands the ModelAndView object to the ViewResoler for processing and returns the specified View View to the front-end controller.

⑤ The DispatcherServlet renders the View (that is, populates the View with model data). A View is an interface whose implementation classes support different View types (JSP, FreeMarker, Thymleaf, etc.).

⑥ DispatcherServlet sends the page response to the user.

5. What is MyBatis primary and secondary cache?

Level 1 cache: The scope is SqlSession. The same SQL query (same SQL and parameters) is executed in the same SqlSession. The first time the database is queried and written to the cache and the second time it is directly fetched from the cache.

  • Level 1 caching is a HashMap local cache based on PerpetualCache and level 1 caching is enabled by default.

  • Invalid policy: If an operation is added, deleted, or changed between two SQL queries, such as INSERT, UPDATE, or delete, the SqlSession cache is cleared after the COMMIT.

Level 2 cache: The scope is NameSpace level. Multiple SQLsessions can operate SQL statements in Mapper files of the same NameSpace. Multiple SQLsessions can share level 2 cache. (Even if there are two Mappers, the data from the SQL query executed in the two Mappers will be stored in the same level 2 cache area).

  • The level 2 cache is also a HashMap local cache based on PerpetualCache, with custom storage sources such as Ehcache/Redis etc. Level 2 caching is disabled by default.

  • Operation process: The SQL under a NameSpace is invoked for the first time to query information. The queried information is stored in the level-2 cache area corresponding to the Mapper. When the same SQL in the Mapper mapping file under the same NameSpace is called for the second time to query information, the result will be fetched from the corresponding level 2 cache.

  • Invalid policy: After the SQL is added, deleted, or modified in the Mapepr mapping file of the same NameSpace and the COMMIT operation is performed, the level-2 cache is cleared.

Note: When implementing level 2 caching, MyBatis recommends that poJOs returned be Serializable, which means that it recommends implementing the Serializable interface.

As shown in the figure:

When Mybatis calls THE Dao layer to query the database, it first queries the second-level cache, and there is no corresponding data in the second-level cache, then queries the first-level cache, and there is no corresponding data in the first-level cache, and finally goes to the database to search.

Why Mybatis is a semi-automatic ORM mapping tool? What’s the difference between it and automatic?

What is ORM?

Object Relational Mapping (ORM) is a technology to establish a Mapping relationship between Relational database data and simple Java objects (POJOs).

Mybatis semi-automatic ORM mapping tool What’s the difference between it and automatic?

  • First of all, Hibernate and JPA are fully automatic ORM mapping tools. When Hibernate is used to query associated objects or associated collection objects, it can be directly obtained according to the object relational model, so it is fully automatic.

  • While Mybatis needs to write SQL manually when querying associated objects or associated collection objects, so it is called semi-automatic ORM mapping tool.

  • In other words, one of the main reasons MyBatis is semi-automatic ORM is that it requires manual or plug-in generation of SQL in XML or annotations to complete SQL execution results and object mapping binding.

7. Can you briefly tell me the loading process of Mybatis?

  • MyBatis is built around an instance of SqlSessionFactory, which can be obtained from SqlSessionFactoryBuilder.

  • SqlSessionFactoryBuilder can build an instance of SqlSessionFactory from an XML Configuration file or a pre-configured Configuration instance.

  • The SqlSessionFactory instance factory can produce SQLSessions, which provide all the methods needed to execute SQL commands in the database.

Specific process:

① Loading the configuration file: The configuration files to be loaded include the global configuration file (Mybatis -config. XML) and the SQL(mapper.xml) mapping file. The global configuration file configur es the operating environment information of Mybatis (data source, transaction, etc.). The SQL mapping file is configured with information related to SQL execution.

MyBatis constructs the SqlSessionFactory by reading the configuration file, that is, SqlSessionFactory by SqlSessionFactoryBuilder.

(3) Create a session: MyBatis can create a session object (SqlSession) with the session factory. A session object is an interface that contains add, delete, change, and query methods for database operations.

(4) Create an Executor: Because the session object itself cannot operate directly on the database, it uses an interface called a database Executor to perform operations for it.

⑤ Encapsulate SQL objects: An Executor encapsulates the SQL information to be processed in an object (MappedStatement). This object includes SQL statements, input parameter mapping information (Java simple types, HashMap, or POJO), and output result mapping information (Java simple types, HashMap, or POJO).

⑥ Operation database: with the executor and SQL information encapsulation object to use them to access the database, and finally return the operation results, end the process.

What is Spring level 3 caching?

The so-called triple cache, in fact, the org. Springframework. Beans. The factory under the package DefaultSingletonBeanRegistry three members of the class attribute:

  • Spring level 1 cache: Used to hold objects that have been instantiated and initialized

Key: beanName

Value: the Bean instance

private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

  • Spring level 2 cache: Used to hold objects that are instantiated but not initialized

Key: beanName

Value: the Bean instance

Unlike singletonObjects, when a singleton bean is placed in it, it can be retrieved from the getBean method while the bean is being created. The purpose of this method is to loop through references!

private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

  • Spring level 3 cache: Used to hold an object factory that provides an anonymous inner class for creating objects in the level 2 cache

Key: beanName

Value: Factory for the Bean

private final Map<String, ObjectFactory<? >> singletonFactories = new HashMap<>(16);

As shown, except for the tertiary cache, which is a HashMap, the other two are concurrenthashMaps:

Spring introduced level 3 caching to solve the problem of loop dependencies!

In addition to the three Map sets above, there is another set also mentioned here:

Used to hold all currently registered beans

private final Set registeredSingletons = new LinkedHashSet<>(256);

What are Spring cycle dependencies? How to solve it?

First, Spring addresses loop dependencies with two prerequisites:

  • Circular dependencies caused by Setter injection (constructor injection not possible)

  • It must be a singleton

In essence, the solution to the problem of cyclic dependency is to rely on the three-level cache to retrieve uninitialized objects in advance. Let’s look at an example of a cyclic dependency:

The creation process of object A:

1. Create object A and place object A factory in level 3 cache when instantiating

2. When user A injects attributes, user A relies on user B and instantiates user B

3. When creating object B, it is found that object A is dependent on object A. Query A from level 1 to level 3 cache once, get A from level 3 cache through object factory, put A into level 2 cache, and delete A from level 3 cache.

4. Create object A from level 1 cache, get the instantiated and initialized object B from level 1 cache, delete A from level 2 cache, and add A to level 1 cache.

5. Finally, level 1 cache holds objects A and B that have been instantiated and initialized.

As you can see from the analysis of step 5 above, the three-level cache solves the loop dependency by separating the instantiation and initialization processes, so there is no way to separate this operation if you use constructors (because constructor injection instantiation and initialization are done together). Therefore, constructor injection does not solve the problem of loop dependency.

Why do we need level 3 caching to solve loop dependencies? Not level two?

Answer: No!

Using level 3 cache instead of level 2 cache is not just because level 3 cache is the only way to solve the circular reference problem, but level 2 cache is also very good at solving the circular reference problem.

Using level 3 caching instead of level 2 caching is not for IOC’s sake, but for AOP’s sake. In the case of level 2 caching, a normal Bean object is put into the level 2 cache. BeanPostProcessor generates the proxy object and overwrites the normal Bean object in the level 2 cache. So in a multi-threaded environment you might get different objects.

  • In short, AOP proxy enhancements to beans can overwrite earlier objects, which can result in inconsistent fetching of objects if multithreaded

10. What design patterns are used in Spring?

Singleton pattern: Beans in Spring are singleton by default. Needless to say.

Factory pattern: The factory pattern mainly produces Bean objects through the BeanFactory and ApplicationContext.

Proxy mode: The most common way to implement AOP is through proxies. Spring uses JDK dynamic proxies and CGLIB proxies.

The singleton pattern

Usage scenarios of singleton mode:

The business system needs only one object instance globally, such as transmitter, Redis connection object, etc.

Beans in the Spring IOC container are singletons by default.

Dependency injection objects in the Controller, Service, and Dao layers of Spring Boot via @autowire are singletons by default.

Singleton pattern classification:

Slacker: This is lazy loading, delaying the creation of objects until they are needed.

Hungry: As opposed to lazy, create objects ahead of time.

Implementation steps of singleton pattern:

Privatize constructor.

Provides methods to get singletons.

The factory pattern

Factory pattern introduction: It provides an optimal way to create objects without exposing creation logic to clients, and by using a common interface to point to newly created objects.

The factory pattern can be implemented in three different ways:

(1) Simple factory mode (static factory) : by passing in the relevant type to return the corresponding class, this way is relatively simple, scalability is relatively poor.

② Factory method pattern: by implementing the class to achieve the corresponding method to determine the corresponding return result, this way is relatively strong scalability.

(3) Abstract factory mode: Based on the expansion of the above two modes, and support refined products.

Application Scenarios:

Decoupling: Separation of responsibilities to separate the creation and use of complex objects.

Reusing code reduces maintenance costs: if object creation is complex and needs to be used in multiple places, if you write everywhere, you have a lot of duplicate code, and if the business logic changes, you need to change it everywhere. Using the factory pattern for unified creation, you can simply modify the factory class to reduce costs.

The proxy pattern

The most intuitive explanation of the proxy pattern is that, through the proxy, the prosteed object is “enhanced”! (that is, extending the functionality of the proxied object)

The proxy mode is divided into static proxy and dynamic proxy: the dynamic proxy proxy class is dynamically generated, the static proxy class is our pre-written logic.

Dynamic proxies can be implemented in Java in two ways:

JDK dynamic proxy

CGLIB dynamic proxy

Today’s share has ended, please forgive and give advice!