2021 Java backend Engineer Interview Guide – (SSM)

Time:2021-9-23

preface

The text has been included in my GitHub warehouse. Welcome Star: https://github.com/bin3923282…
The best time to plant a tree is ten years ago, followed by now

Tips

The interview guide series, in many cases, does not dig into the details. It is a way for Xiao Liu to review the knowledge in the role of the interviewee, so I default that most of the things, as an interviewer, you must understand.

https://www.processon.com/vie…

The above is the brain map address

Ramble

SSM framework, which we usually use most, is often asked in interviews. Today we’ll take a look at these frameworks

Then the following is a summary of the previous articles

  • 2021 Java backend Engineer Interview Guide – (Introduction)
  • 2021 Java backend Engineer Interview Guide – (Java Basics)
  • 2021 Java backend Engineer Interview Guide – (concurrent multithreading)
  • 2021 Java backend Engineer Interview Guide – (JVM)
  • 2021 Java backend Engineer Interview Guide – (MySQL)
  • 2021 Java backend Engineer Interview Guide – (redis)
  • 2021 Java backend Engineer Interview Guide – (elasticsearch)
  • 2021 Java backend Engineer Interview Guide – (message queue)

What is spring

Spring is a lightweight development framework, which aims to improve the development efficiency of developers and the maintainability of the system. Generally speaking, spring framework refers to the spring framework, which is a collection of many modules. Using these modules can easily assist us in development. These modules are: core container, data access / integration, web, AOP (aspect oriented programming), tools, messages and test modules. For example, the core component in the core container is the core of all spring components, the beans component and context component are the basis for implementing IOC and dependency injection, and the AOP component is used to implement aspect oriented programming.

Talk about your understanding of spring IOC and AOP

IOC (inverse of control) is a design idea, which is to hand over the control of manually creating objects in the program to the spring framework. IOC is also used in other languages and is not unique to spring. The IOC container is the carrier used by spring to implement IOC. The IOC container is actually a map (key, value). Various objects are stored in the map.

The interdependence between objects is managed by IOC container, which completes the object injection. This can greatly simplify the development of applications and liberate applications from complex dependencies. The IOC container is like a factory. When we need to create an object, we only need to configure the configuration file / annotation, regardless of how the object is created. In an actual project, a service class may have hundreds or even thousands of classes as its bottom layer. If we need to instantiate the service, you may have to find out the constructors of all the bottom classes of the service every time, which may drive people crazy. If you use IOC, you only need to configure it and reference it where necessary, which greatly increases the maintainability of the project and reduces the difficulty of development.

AOP (aspect oriented programming) can encapsulate the logic or responsibilities (such as transaction processing, log management, permission control, etc.) that have nothing to do with the business but are jointly invoked by the business modules, so as to reduce the repeated code of the system, reduce the coupling between modules, and facilitate the scalability and maintainability in the future.

Spring AOP is based on dynamic proxy. If the object to be proxy implements an interface, spring AOP will use JDK proxy to create proxy objects. For objects that do not implement interfaces, JDK proxy cannot be used for proxy. At this time, spring AOP will use cglib, At this time, spring AOP will use cglib to generate a subclass of the proxied object as a proxy

Generally, we can use AspectJ. Spring AOP has integrated AspectJ. AspectJ should be the most complete AOP framework in the Java ecosystem.

After using AOP, we can abstract some general functions and use them directly where needed, which greatly simplifies the amount of code. It is also convenient when we need to add new functions, which also improves the scalability of the system. AOP is used in logging function, transaction management and other scenarios.

What’s the difference between spring AOP and AspectJ AOP? Which do you usually use in the project

Spring AOP is a runtime enhancement, while AspectJ is a compile time enhancement. Spring AOP is based on proxying, while AspectJ is based on bytecode manipulation.

Spring AOP has integrated AspectJ, which should be regarded as the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than spring AOP, but spring AOP is relatively simpler,

We generally use AspectJ AOP in many projects

Spring bean scope type. Is spring bean thread safe

Whether the beans in the spring container are thread safe or not, and the container itself does not provide the thread safety policy of beans. Therefore, it can be said that the beans in the spring container do not have thread safety characteristics, but it should be studied in combination with the beans in the specific scope.

Spring’s bean scope type

  • Singleton: singleton, default scope.
  • Prototype: prototype, creating one new object at a time.
  • Request: request. Each HTTP request creates a new object, which is applicable to the webapplicationcontext environment.
  • Session: session. The same session shares an instance, and different sessions use different instances.

The problem of thread safety should be explained separately from the singleton and the prototype bean.

  • For the prototype bean, each time a new object is created, that is, there is no bean sharing between threads. Naturally, there will be no thread safety problem.
  • For a singleton bean, all threads share a singleton bean, so there is a competition for resources.
  • If a singleton bean is a stateless bean, that is, the operations in the thread will not perform operations other than queries on the members of the bean, then the singleton bean is thread safe. For example, spring MVC’s controller, service, Dao, etc. most of these beans are stateless and only focus on the method itself.

To sum up

  • In containers such as @ controller / @ service, by default, the scope value is singleton, which is also thread unsafe.
  • Try not to define static variables in containers such as @ controller / @ service. Whether it is a singleton or a prototype, it is thread unsafe.
  • The bean object injected by default is thread unsafe when the scope is not set.
  • If you must define variables, use ThreadLocal to encapsulate them. This is thread safe

What’s the difference between @ component and @ bean?

  • The working objects are different: @ Component annotation works on classes, while @ bean annotation works on methods.
  • @Components are usually automatically detected and assembled into the spring container through classpath scanning (we can use the @ componentscan annotation to define the path to be scanned, find out the classes that need to be assembled, and automatically assemble them into the spring bean container)@ Bean annotation is usually defined in the method marked with this annotation to generate this bean, @ bean tells spring that this is an example of a class and returns it to me when I need to use it.
  • @Bean annotation is more customizable than Component annotation, and in many places we can only register beans through @ bean annotation. For example, when we reference a class in a third-party library and need to assemble it into the spring container, it can only be implemented through @ bean.

What is spring assembly and what are the ways of automatic assembly?

When beans are grouped together in a spring container, it is called an assembly or bean assembly. The spring container needs to know what beans are needed and how the container should use dependency injection to bind beans together and assemble beans at the same time.

The spring container can assemble beans automatically. In other words, spring can automatically parse bean collaborators by checking the contents of beanfactory.

Different modes of automatic assembly:

  • No – this is the default setting, indicating that there is no automatic assembly. Explicit bean references should be used for assembly.
  • Byname – it injects object dependencies based on the name of the bean. It matches and assembles beans whose properties are defined by the same name in the XML file.
  • Bytype – it injects object dependencies based on the type. If the type of the attribute matches a bean name in the XML file, match and assemble the attribute.
  • Constructor – it injects dependencies by calling the constructor of the class. It has a large number of parameters.
  • Autodetect – first, the container tries to use autowire assembly through the constructor, and if not, tries to use bytype auto assembly.

Do you know what the @ Autowired annotation is for? What about @ qualifier?

  • @Autowired can more accurately control where and how automatic assembly should be carried out. This annotation is used to automatically assemble beans on setter methods, constructors, properties or methods with arbitrary names or multiple parameters. By default, it is type driven injection.
  • When you create multiple beans of the same type and want to assemble only one of them with properties, you can use the @ qualifier annotation and @ Autowired to disambiguate by specifying which exact bean should be assembled.

Talk about the life cycle of spring bean

It is very necessary to accurately understand the life cycle of spring beans. We usually use ApplicationContext as the spring container. Here, we are also talking about the life cycle of beans in ApplicationContext. In fact, beanfactory is similar, but the processor needs to be registered manually.
2021 Java backend Engineer Interview Guide - (SSM)
2021 Java backend Engineer Interview Guide - (SSM)

In fact, in the whole bean life cycle, that is, before the bean initialization is completed, our spring provides us with too many expansion points, which allows us to flexibly solve our different needs. Let’s summarize these hook functions
The complete life cycle of a bean has experienced various method calls, which can be divided into the following categories:

  • Bean’s own method: This includes the method called by the bean itself and the method specified through the init method and destroy method of < bean > in the configuration file
  • Bean – level life – cycle interface methods: This includes beannameaware, beanfactoryaware, initializingbean, and diposablebean interface methods
  • Container level life cycle interface method: This includes two interface implementations, instantiawarebeanpostprocessor and beanpostprocessor. Their implementation classes are generally called “postprocessors”.

2021 Java backend Engineer Interview Guide - (SSM)

Let’s talk about the startup process of web container and its startup mode

First of all, let’s talk about the startup method of spring container, that is, a startup method of our whole web project. At present, mainstream companies are generally divided into two types: one is the startup process based on SSM, and the other is the startup process based on springboot. Today I’ll talk about a startup process of SSM. The next time springboot will be talked about together with the springcloud series

Starting process of spring boot of SSM
2021 Java backend Engineer Interview Guide - (SSM)

  • Firstly, for a web application, it is deployed in the web container, which provides a global context environment. This context is ServletContext, which provides a host environment for the following spring IOC container;
  • Then there is our web.xml. I think we all encountered it in the project a few years ago. Contextloaderlistener will be provided in web.xml. When the web container is started, the container initialization event will be triggered. At this time, the contextloaderlistener will listen to this event, and its contextinitialized method will be called. In this method, spring will initialize a startup context, which is called the root context, that is, webapplicationcontext, which is an interface class. To be exact, Its actual implementation class is xmlwebapplicationcontext. This is the IOC container of spring. The configuration of the corresponding bean definition is specified by the context param tag in web.xml. After the IOC container is initialized, spring takes webapplicationcontext.rootwebapplicationcontextattribute as the attribute key and stores it in ServletContext for easy access;
  • Thirdly, after the contextloaderlistener listener is initialized, it starts to initialize the servlet configured in web.xml. Here is the dispatcher servlet. This servlet is actually a standard front-end controller to forward, match and process each servlet request. Dispatcherservlet context will establish its own IOC context during initialization to hold spring MVC related beans. When establishing the dispatcher servlet’s own IOC context, webapplicationcontext.rootwebapplicationcontextattribute will be used to obtain the previous root context (i.e. webapplicationcontext) from the servlet context as the parent context of its own context. After you have this parent context, you can initialize your own context. The dispatcher servlet initializes its own context, which can be seen in its initstrategies method. The general work is to initialize processor mapping, view parsing, etc. The default implementation class of the servlet’s own context is also xmlwebapplicationcontext. After initialization, spring takes the attribute related to the servlet name (the servlet name is not simply the key here, but through some transformations, you can view the source code yourself) as the attribute key, and also saves it in the ServletContext for subsequent use. In this way, each servlet holds its own context, that is, it has its own independent bean space, and each servlet shares the same beans, that is, those beans defined by the root context (the context initialized in step 2).

The above is the start-up process of our whole SSM. It is also a whole project start-up process developed by most enterprises a few years ago. As for the way of springboot, the next springboot will be in

Let’s talk about the loading process of spring container (IOC startup process)

The above process is the start-up process of the whole web container, which includes the start-up process of our spring container. Now I will explain in detail the loading process of our IOC start-up

The refresh () method in abstractapplicationcontext. Java is the complete code of the whole IOC container construction process. As long as you understand every line of code in this method, you basically understand most of the principles and functions of IOC.
2021 Java backend Engineer Interview Guide - (SSM)

  • Preparerefresh() method: prepare a new context for refresh, set its start date and activity flag, and initialize some properties. It’s mainly some preparatory work. It’s not a very important method. You can ignore it first
  • Obtainfreshbeanfactory() method: this method will parse all spring configuration files (usually we will put them in the resources directory), encapsulate the bean definitions in all spring configuration files into beandefinition and load them into beanfactory. In common, if the < context: component scan base package = “com. Joonwhee. Open” / > annotation is parsed, the directory specified by the base package will be scanned, and the bean definitions using the specified annotation (@ controller, @ service, @ component, @ repository) in this directory will also be encapsulated as beandefinition and loaded into beanfactory. The content of “load into beanfactory” mentioned above mainly refers to the following three caches:

    • Beandefinitionnames cache: the beanname collection of all beans loaded into beanfactory.
    • Beandefinitionmap cache: beanname and beandefinition maps of all beans loaded into beanfactory.
    • Aliasmap cache: beanname and alias mapping of all beans loaded into beanfactory.
  • Preparebeanfactory (beanfactory) method: configure the standard context features of beanfactory, such as the classloader and post processor of the context. This method will register three default environment beans: environment, SystemProperties and systemenvironment, and register two bean post processors: applicationcontextawareprocessor and applicationlistenerdetector.
  • Postprocessbeanfactory (beanfactory) method: allows subclasses to perform subsequent processing on beanfactory. The default implementation is empty and left to subclasses for implementation.
  • Invokebeanfactoryprocessors (beanfactory) method: instantiate and call all beanfactoryprocessors, including its subclass beandefinitionregistrypostprocessor.
  • Register beanpostprocessors (beanfactory) method: register all beanpostprocessors and load all classes that implement the beanpostprocessor interface into beanfactory.
  • Initmessagesource() method: initializes the message resource MessageSource
  • Initapplicationeventmulticast() method: initializes the applied event broadcaster applicationeventmulticast.
  • Onrefresh () method: this method is a template method and is provided to the subclass extension implementation. It can be overridden to add context specific refresh work. The default implementation is empty. (in spring boot, this method can load the Tomcat container.)
  • Registerlisteners() method: register listeners.
  • Finishbeanfactoryinitialization (beanfactory) method: this method instantiates all remaining non lazy loading singleton beans. In addition to some internal beans, beans that implement the beanfactoryprocessor interface and beans that implement the beanpostprocessor interface, other non lazy loading singleton beans will be instantiated in this method, and the trigger of beanpostprocessor is also in this method. (this method is actually the core method, including our bea from beandifinition to the core method of beans in our container)
  • Finishrefresh() method: complete the refresh of this context, mainly pushing the context refresh completion event (contextrefreshedevent) to the listener.

The following points are more important

  • Obtainfreshbeanfactory creates a new beanfactory, reads and parses bean definitions.
  • Invokebeanfactoryprocessors provides developers with the ability to extend beanfactory.
  • Registerbeanpost processors provide developers with the ability to extend beans.
  • Finishbeanfactoryinitialization instantiates all remaining non lazy loaded singleton beans.

Do you understand how spring MVC works? Page based controller type

  • The client (browser) sends a request directly to the dispatcher servlet.
  • Dispatcherservlet calls handlermapping according to the request information to parse the handler corresponding to the request.
  • After resolving to the corresponding handler (that is, the controller controller we usually call), it is processed by the handleradapter adapter.
  • The handleradapter will call the real processor according to the handler to process the request and process the corresponding business logic.
  • After processing the business, the processor will return a modelandview object. Model is the returned data object and view is a logical view.
  • Viewresolver will find the actual view based on the logical view.
  • Dispatcher servlet passes the returned model to view (view rendering).
  • Return view to requester (browser)

What design patterns are used in the spring framework?

  • Factory design pattern: spring uses factory pattern to create bean objects through beanfactory and ApplicationContext.
  • Proxy design pattern: implementation of spring AOP function.
  • Singleton design pattern: beans in spring are singleton by default.
  • Template method pattern: JDBC template, hibernate template and other classes in spring that operate on the database ending in template use the template pattern.
  • Observer pattern: spring event driven model is a classic application of observer pattern.
  • Adapter mode: the spring AOP enhancement or advice uses the adapter mode, and the spring MVC also uses the adapter mode to adapt the controller.

Spring transactions are not familiar. Which implementation method do you usually use

  • Programming transactions, hard coded in code. (not recommended)
  • Declarative transaction, configured in the configuration file (recommended)

Generally, in the process of our enterprise development, declarative transactions are generally used. Declarative transactions are also divided into two types: one is based on XML and the other is based on annotation, which is generally annotated multipoint

What are the transaction propagation behaviors in spring transactions?

Current transaction support:

  • TransactionDefinition.PROPAGATION_ Required: if a transaction currently exists, join the transaction; If there is no current transaction, a new transaction is created.
  • TransactionDefinition.PROPAGATION_ Supports: if a transaction currently exists, join the transaction; If there are currently no transactions, continue to run in a non transactional manner.
  • TransactionDefinition.PROPAGATION_ Mandatory: if a transaction currently exists, join the transaction; Throw an exception if there is no current transaction. (mandatory: mandatory)

The current transaction is not supported:

  • TransactionDefinition.PROPAGATION_ REQUIRES_ New: create a new transaction. If there is a current transaction, suspend the current transaction.
  • TransactionDefinition.PROPAGATION_ NOT_ Supported: run in non transaction mode. If there is a transaction, suspend the current transaction.
  • TransactionDefinition.PROPAGATION_ Never: runs in a non transactional manner. If there is a transaction, an exception will be thrown.

Tell me the difference between beanfactory and factorybean?

  • Beanfactory is a factory, i.e. IOC container or object factory. In spring, all beans are managed by beanfactory (i.e. IOC container), which provides the functions of instantiating and fetching objects.
  • Factorybean is a bean. This bean is not a simple bean, but a factory bean that can produce or modify objects. Its implementation is similar to the factory pattern and modifier pattern in design pattern.

Let’s talk about spring’s circular dependency

  • Spring’s circular dependency mainly means that two classes automatically inject each other through @ Autowired dependency, that is, class A contains an object reference of class B and needs automatic injection, and class B contains an object reference of class A and needs automatic injection.
  • For the circular dependency problem, spring adopts different processing strategies according to different injection methods. If both sides use attribute value injection or setter method injection, spring can automatically solve the circular dependency injection problem and the application can be started successfully; If both parties use the constructor to inject into each other or the main bean object (the bean object loaded first during spring startup) uses the constructor to inject, spring cannot solve the circular dependency injection, and the program cannot be started when an error is reported.

First, spring supports circular reference by default in the case of singleton; Without any configuration, two beans can be initialized successfully if they depend on each other; In the spring source code, when creating a bean, first create the object of the bean. After the object is created, determine whether to allow the temporary object to be cached by judging the allowcircularreferences attribute of the container object. If it can be cached successfully, expose the temporary object in advance by caching to complete the circular dependency; This attribute is true by default, so spring supports circular dependency by default, but spring provides an API for programmers to modify this attribute, so spring also provides the function of turning off circular reference;

How does spring solve circular reference

First, spring internally maintains three maps, which are commonly referred to as the three-level cache.

The author did not find the concept of three-level cache after reading the spring documents. It may also be a local vocabulary for ease of understanding.

In the defaultsingletonbeanregistry class of spring, you will find these three maps hanging above the class:

  • Singletonobjects is our most familiar friend, commonly known as “Singleton pool” and “container”, which is the place where the singleton bean is created.
  • The singletonfactories map creates the original factory of the bean
  • Earlysingletonobjects is an early reference to the mapping bean, that is, the bean in this map is not complete, it can’t even be called “bean”, it’s just an instance

The last two maps are actually at the “stepping stone” level, but they are used to help when creating beans, and they are cleared after creation.

Therefore, the author was confused about the word “L3 cache” earlier, probably because the comments start with cache of.

Why do you use the last two maps as stepping stones? Suppose that the bean finally placed in singletonobjects is a cup of “cool and white” you want.

Then spring prepared two cups, singleton factories and earlysingletonobjects, to “toss” back and forth several times, and put the hot water in singleton objects.

In different scenarios of circular reference, what methods can be used to solve circular reference

2021 Java backend Engineer Interview Guide - (SSM)

Why can’t some injection methods solve the problem of circular dependency? It can be seen from the source code that they do not use the earlysingletonobjects cache, so they can’t solve the circular dependency

Some ways to solve circular dependencies that spring cannot solve

If there is a circular dependency problem in the project, it indicates that it is a circular dependency that spring cannot solve by default. It depends on the print log of the project and what kind of circular dependency it belongs to. At present, it includes the following situations:
2021 Java backend Engineer Interview Guide - (SSM)

Generate circular dependencies generated by proxy objects
There are many solutions to such circular dependency problems, mainly including:

  • Use @ lazy annotation to delay loading
  • Use the @ dependson annotation to specify the loading order relationship
  • Modify the file name and change the loading order of circular dependency classes

What is mybatis?

  • Mybatis is a semi ORM (object relational mapping) framework. It internally encapsulates the complicated processes of JDBC, loading drivers, creating connections, creating statements, etc. when developing, developers only need to pay attention to how to write SQL statements, which can strictly control the SQL execution performance and has high flexibility.
  • As a semi ORM framework, mybatis can use XML or annotations to configure and map native information, map POJOs to records in the database, and avoid almost all JDBC code, manually setting parameters and obtaining result sets.

What is the difference between #{} and ${}?

  • {} is precompiled and ${} is string substitution.

  • When mybatis processes #{}, it will replace #{} in SQL with #{}? Number, call the set method of Preparedstatement to assign value;
  • When mybatis processes ${}, it replaces ${} with the value of the variable.
  • Using #{} can effectively prevent SQL injection and improve system security.

Talk about the level 1 and level 2 cache of mybatis:

L1 cache transaction scope: the cache can only be accessed by the current transaction. The life cycle of the cache depends on the life cycle of the transaction. When the transaction ends, the cache ends its life cycle. In this range, the cached media is memory. L2 cache process scope: the cache is shared by all transactions within the process. These transactions may access the cache concurrently, so the necessary transaction isolation mechanism must be adopted for the cache. The life cycle of the cache depends on the life cycle of the process. When the process ends, the cache ends its life cycle. Process wide cache may store a large amount of data, so the storage medium can be memory or hard disk.

Let’s talk about the overall architecture of mybatis

2021 Java backend Engineer Interview Guide - (SSM)

Actually, I think we know what the mybatis framework needs to do. Why? In fact, if we don’t have mybatis, we can also do database operations, right? That’s the operation of JDBC. In fact, mybatis is just a framework encapsulated on JDBC. What it needs to do is so much. Let me summarize

  • The first is some basic component connection management, transaction management, configuration loading and cache processing
  • Then there are the core functions, our parameter mapping, our SQL parsing, SQL execution, and our result mapping
  • Just encapsulate our unified crud interface. That’s all.

The above is what the whole mybatis does. Of course, it is not so simple to handle each function.

Are you familiar with the source code of mybatis? Talk to a place you are familiar with

2021 Java backend Engineer Interview Guide - (SSM)

The above figure is a core process of the whole mybatis. In fact, all frameworks, whether spring or mybatis, can be divided into two parts. One is the initialization process, which is equivalent to the process of getting ready to receive customers. The second is the actual process of receiving customers. Therefore, the source code of any framework comes from this way, Mybatis is certainly no exception

  • Initialization process

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(“configuration.xml”));

The core of mybatis is in sqlsessionfactory. First, build sqlsessionfactory. This process involves parsing various configuration files. The first one to be parsed is configuration. Then there are many tags in it, such as properties, and then there is a mapper node, We can find our mapper.xml, then parse the nodes inside, report various caches, select, etc., and then bind the parsed XML to our mapper interface through the namespace, generate code objects, and put them into the map container konwsmapper. Finally, the sqlsessionfactory can be generated

  • Real execution process

When our mybatis is ready? After we get the sqlsession object, if we don’t want spring integration, then of course we need to get our mapper object sqlsession.getmapper. Of course, the obtained proxy object is also pulled, and then to mappermethod, and then sqlsession forwards the query method to the executor. The executor accesses the database based on JDBC to obtain data. The executor converts the data into POJOs through reflection and returns it to sqlsession. Returns data to the caller.

end

Next, let’s take a look at the components of springboot and springcloud. There are still a lot of things. Let’s go

Daily praise

Well, everyone, that’s all the content of this article. All the people who can see here areTrue powder

Creation is not easy. Your support and recognition is the biggest driving force for my creation. See you in the next article

Wechat search “program life of six pulse divine sword” reply 888 has a lot of information I’m looking for to give you

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]