preface

Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now

Tips

The interview guide series, which in many cases does not delve into the details, is a way for students to review their knowledge in the role of the interviewee, so I assume that most of the things you, as the interviewer, know.

www.processon.com/view/link/6…

This is the brain map address

Where t

SSM framework, this is the most we usually use, so the interview is often asked, today we will take a look at the framework

Then below is a summary of previous articles

  • 2021-Java Backend Engineer Interview Guide (Introduction)
  • 2021-Java Backend Engineer Interview Guide
  • 2021-Java Backend Engineer Interview Guide -(Concurrency – Multithreading)
  • 2021-Java Backend Engineer Interview Guide -(JVM)
  • 2021-Java Backend Engineer Interview Guide -(MySQL)
  • 2021-Java Backend Engineer Interview Guide -(Redis)
  • Java Backend Engineer Interview Guide -(Elasticsearch)
  • 2021-Java Backend Engineer Interview Guide -(Message Queue)

What is the Spring

Spring is a lightweight development framework designed to improve developer productivity and system maintainability. We generally refer to the Spring Framework, which is a collection of modules that can be used to facilitate development. These modules are: core container, data access/integration, Web, AOP (aspect oriented programming), tools, messaging, and test modules. For example, the Core component in Core Container is the Core of all Spring components, the Beans component and Context component are the basis for IOC and dependency injection, and the AOP component is used to implement tangential programming.

Talk about your understanding of Spring IoC and AOP

IoC is a design concept that hands over Control of manually created objects in programs to the Spring framework. IoC is also used in other languages, not specific to Spring. IoC container is the carrier used by Spring to implement IoC. IoC container is actually a Map (key, value), which stores various objects.

The interdependencies between objects are managed by the IoC container and the object injection is completed by the IoC container. This greatly simplifies application development and frees applications from complex dependencies. The IoC container is like a factory. When we need to create an object, all we need to do is configure the configuration file/annotations, regardless of how the object was created. In a real project, a Service class might have hundreds or even thousands of classes as its underlying class. If we need to instantiate the Service, you might have to figure out the constructors of all the underlying classes of the Service every time, which can drive people crazy. With IoC, all you need to do is configure it and then reference it where you need it, which makes your project much more maintainable and easier to develop.

AOP(aspect-oriented Programming: section-oriented Programming) can encapsulate the logic or responsibility (such as transaction processing, log management, permission control, etc.) that has nothing to do with business but is called jointly by business modules, so as to reduce the repeated code of the system and reduce the coupling degree between modules. And is conducive to the future scalability and maintainability.

Spring AOP is based on dynamic proxies. If you want to Proxy an object that implements an interface, Spring AOP uses JDK Proxy to create Proxy objects. If you don’t implement an interface, you can’t use JDK Proxy to Proxy objects. In this case, Spring AOP uses Cglib, which generates a subclass of the proxied object as the proxy.

AspectJ can be used in general. Spring AOP already integrates with AspectJ, and AspectJ is probably the most complete AOP framework in the Java ecosystem.

With AOP, we can abstract out some common functions and use them where needed, which greatly simplifies the amount of code. It is also convenient when we need to add new features, which also improves system scalability. Logging capabilities, transaction management, and other scenarios use AOP.

What are the differences between Spring AOP and AspectJ AOP? Which one do you usually use in a project

Spring AOP is runtime enhancement, while AspectJ is compile-time enhancement. Spring AOP is based on Proxying, while AspectJ is based on Bytecode Manipulation.

Spring AOP already integrates with AspectJ, which is arguably the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simple,

AspectJ AoP is often used more often in projects

Spring’s bean scope type, whether Spring beans are thread-safe

Whether the beans in the Spring container are thread-safe or not, the container itself does not provide a thread-safe policy for beans, so it can be said that the beans in the Spring container do not have thread-safe features, but the specific scope of beans should be combined to study.

Spring’s bean scope type

  • Singleton: singleton, default scope.
  • Prototype: Create a new object at a time.
  • Request: creates a new object for each Http request. This object applies to WebApplicationContext.
  • Session: the same session shares one instance, and different sessions use different instances.

Thread safety is addressed separately in terms of singletons and prototype beans.

  • With prototype beans, there are no thread-safety issues when a new object is created each time, meaning that there is no Bean sharing between threads.
  • With singleton beans, all threads share a singleton instance Bean, so there is competition for resources.
  • A singleton Bean is thread-safe if it is a stateless Bean, meaning that operations in a thread do not perform operations other than queries on members of the Bean. For example, Spring MVC’s Controller, Service, Dao, etc., these beans are mostly stateless and only focus on the method itself.

Conclusion under

  • In containers such as @Controller/ @service, by default, scope values are singleton and thread-unsafe.
  • Try not to define static variables in @controller / @service containers. Singletons and prototype instances are thread unsafe.
  • The default injected Bean object is also thread-unsafe without scope.
  • If you must define variables, encapsulate them with ThreadLocal, which is thread-safe

What’s the difference between @Component and @Bean?

  • The object is different: the @Component annotation applies to classes, while the @Bean annotation applies to methods.
  • The @Component is usually automatically detected and assembled into the Spring container via classpath scanning (we can use the @ComponentScan annotation to define the path to be scanned to identify classes that need to be assembled into the Spring bean container). The @bean annotation is usually defined to produce the Bean in a method marked with the annotation. The @bean tells Spring that this is an example of a class and gives it back to me when I need to use it.
  • The @Bean annotation is more customizable than the Component annotation, and in many places we can only register beans through the @Bean annotation. For example, when we reference a class from a third-party library that needs to be assembled into the Spring container, we can only do so through @Beans.

What is Spring assembly? What are the methods of automatic assembly?

When beans are combined together in the Spring container, it is called assembly or bean assembly. The Spring container needs to know what beans are required and how the container should use dependency injection to bind the beans together and assemble them.

The Spring container can automatically assemble beans. That is, Spring can automatically resolve the bean’s collaborators by examining the contents of the BeanFactory.

Different modes of automatic assembly:

  • No – This is the default setting, indicating no autowiring. Assembly should be done using explicit bean references.
  • ByName – It injects object dependencies based on the bean name. It matches and assembles its attributes with beans defined by the same name in the XML file.
  • ByType – It injects object dependencies based on type. If the type of the attribute matches a bean name in the XML file, the attribute is matched and assembled.
  • Constructor – It injects dependencies by calling the constructor of the class. It has a lot of parameters.
  • Autodetect – First the container tries to assemble using Autowire via constructors, and if not, tries byType autoassembly.

Do you know what the @autowired annotation does? The @ the Qualifier?

  • @autoWired gives you more control over where and how autoassembly should take place. 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 using properties, you can use the @Qualifier annotation and @AutoWired to disambiguously specify which exact bean should be assembled.

Talk about the life cycle of Spring Beans

An accurate understanding of the life cycle of Spring beans is essential. We usually use ApplicationContext as the Spring container. Here, we are also talking about the life cycle of the Bean in the ApplicationContext. The BeanFactory is similar, but the handler needs to be manually registered.

In fact, spring provides us with a lot of extension points that allow us to flexibly address our different needs during the whole Bean life cycle, before the Bean is initialized. To summarize, hook function beans go through the full life cycle of various method calls. These methods can be divided into the following categories:

  • Bean’s own methods: This includes methods called by the Bean itself and methods specified by init-method and destroy-method in the configuration file
  • Bean-level lifecycle interface methods: This includes methods for the BeanNameAware, BeanFactoryAware, InitializingBean, and DiposableBean interfaces
  • Container level lifecycle interface methods: this includes InstantiationAwareBeanPostProcessor and BeanPostProcessor these two interface implementation, general said their implementation class for the “processor”.

Let’s talk about the startup process of the Web container and how it starts

First of all, let’s talk about the startup method of Spring container, which is also a startup method of our entire Web project. Currently, mainstream companies generally divide into two kinds, one is based on SSM startup process, the other is based on SpringBoot startup process. Today, I will talk about a startup process of SSM. Springboot next time with springCloud series

SpringBoot startup process of the SSM

  • First, for a Web application deployed in a Web container, the Web container provides its global context, the ServletContext, which provides the hosting environment for the subsequent Spring IoC container.

  • And then there’s our web. XML, which I think you’ve all encountered in a project from a few years ago, which provides contextLoaderListener in web. XML. When the Web container is started, the container initialization event is triggered. The contextLoaderListener listens for this event and its contextInitialized method is called. In this method, Spring initializes a startup context called the root context. WebApplicationContext, which is an interface class, specifically, whose actual implementation class is XmlWebApplicationContext. This is spring’s IoC container, whose Bean definition configuration is specified by the context-param tag in web.xml. In the IoC container after the initialization, spring to WebApplicationContext. ROOTWEBAPPLICATIONCONTEXTATTRIBUTE as Key attributes, store it to the ServletContext, easy to obtain;

  • Again, after the contextLoaderListener is initialized, it initializes the Servlet configured in web.xml, in this case DispatcherServlet, which is actually a standard front-end controller, To forward, match, and process each servlet request. The DispatcherServlet context establishes its own IoC context at initialization to hold spring MVC related beans. When establishing the DispatcherServlet’s own IoC context, Will use WebApplicationContext. ROOTWEBAPPLICATIONCONTEXTATTRIBUTE from ServletContext first before getting the root of the context (i.e. WebApplicationContext) as a context of par Ent context. Once you have the parent context, initialize your own context. The work of this DispatcherServlet initializing its own context can be seen in its initStrategies method, which basically initializes processor mapping, view parsing, and so on. The default context implementation class that the servlet itself holds is also XmlWebApplicationContext. After initialization, Spring takes the property associated with the servlet name (not simply the servlet name Key here, but with some transformation, you can see the source code for yourself) as the property Key and also stores it in the ServletContext for later use. In this way, each servlet holds its own context, that is, its own independent bean space, and each servlet shares the same beans defined by the root context (the context initialized in Step 2).

Above is our entire SSM startup process, is also a few years ago most enterprise development of a whole project startup process oh, as for the way of SpringBoot, the next article in SpringBoot

Why don’t you talk about the Spring container loading process?

The above process is the startup process of the entire Web container, which includes the startup process of our Spring container. I will now give you a detailed explanation of the loading process of our IOC startup

AbstractApplicationContext. Java in the refresh () method, this method is to build the complete code of the whole process of the IoC container, as long as every line of code in this method to understand the most basically know about the principles and functions of the IoC.

  • The prepareRefresh() method: Prepares the new context for the refresh, sets its start date and activity flags, and performs initialization of some properties. Mainly some preparatory work, not very important methods, can be ignored for now
  • ObtainFreshBeanFactory () method: This method parses all Spring configuration files (which we would normally put in the Resources directory), encapsulates the bean definitions in all Spring configuration files as BeanDefinitions, and loads them into the BeanFactory. <context:component-scan base-package=”com.joonwhee.open” /> <context:component-scan base-package=”com.joonwhee.open” /> <context:component-scan base-package=”com.joonwhee.open” /> The bean definitions in this directory that use the specified annotations (@Controller, @Service, @Component, @repository) are also wrapped as BeanDefinitions and loaded into the BeanFactory. The “load into BeanFactory” mentioned above mainly refers to the following three caches:
    • BeanDefinitionNames cache: The beanName collection of all beans loaded into the BeanFactory.
    • BeanDefinitionMap cache: beanName and BeanDefinition mappings for all beans loaded into the BeanFactory.
    • AliasMap cache: beanName and alias maps of all beans loaded into the BeanFactory.
  • PrepareBeanFactory (beanFactory) method: configure the standard context characteristics of the beanFactory, such as the context ClassLoader, post-processor, etc. This method registers three default environment beans: environment, systemProperties, and systemEnvironment, and two bean posthandlers: ApplicationContextAwareProcessor and ApplicationListenerDetector.
  • PostProcessBeanFactory (beanFactory) method: allows subclasses to do subsequent processing on the beanFactory, leaving the default implementation empty and the subclass implementation.
  • InvokeBeanFactoryPostProcessors (the beanFactory) method: All spring BeanFactoryPostProcessor instantiation and calls, including its subclasses BeanDefinitionRegistryPostProcessor.
  • RegisterBeanPostProcessors (the beanFactory) methods: all registered BeanPostProcessor, will all realized the BeanPostProcessor interface class loading in the beanFactory.
  • InitMessageSource () method: Initialize the message resource MessageSource
  • Initialization initApplicationEventMulticaster () method: application of event broadcast ApplicationEventMulticaster.
  • OnRefresh () method: This method is a template method provided to subclass extended implementations that can be overridden to add context-specific refresh work. The default implementation is null. (This method loads the Tomcat container in SpringBoot.)
  • RegisterListeners are registered.
  • FinishBeanFactoryInitialization (the beanFactory) method: this method could not instantiate all the rest of the lazy loading singleton beans. All non-lazy singleton beans are instantiated in this method, except for some internal beans, beans that implement the BeanFactoryPostProcessor interface, and beans that implement the BeanPostProcessor interface. And the BeanPostProcessor trigger is also in this method. (This method is actually the core method, including our BEA from Beandifinition into the core method of our container bean)
  • The finishRefresh() method completes the refresh of this context by pushing the ContextRefreshedEvent to the listener.

More important are the following points

  • ObtainFreshBeanFactory Creates a new BeanFactory, reads and parses the bean definition.
  • Of the BeanFactory invokeBeanFactoryPostProcessors provide developers to extend.
  • RegisterBeanPostProcessors for developers to extend the bean.
  • FinishBeanFactoryInitialization instantiate all the rest of the lazy loading singleton beans.

Do you know how SpringMVC works? Based on the type of page Controller

  • The client (browser) sends the request directly to the DispatcherServlet.
  • The DispatcherServlet invokes HandlerMapping according to the request information and parses the Handler corresponding to the request.
  • After parsing to the corresponding Handler (commonly known as the Controller Controller), it is processed by the HandlerAdapter adapter.
  • The HandlerAdapter calls the actual Handler from the Handler to handle the request and the corresponding business logic.
  • After processing the business, the processor returns a ModelAndView object, Model is the returned data object, and View is a logical View.
  • The ViewResolver finds the actual View based on the logical View.
  • The DispaterServlet passes the returned Model to the View (View rendering).
  • Return the View to the requester (browser)

What design patterns are used in the Spring framework?

  • Factory Design pattern: Spring uses the factory pattern to create bean objects from the BeanFactory, ApplicationContext.
  • Proxy design pattern: Implementation of Spring AOP functionality.
  • Singleton design pattern: Beans in Spring are singleton by default.
  • Template method pattern: Spring’s jdbcTemplate, hibernateTemplate, and other classes that end in Template for database operations use the Template pattern.
  • Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern.
  • Adapter pattern: The adapter pattern is used in Spring AOP enhancements or Advice, and is used in Spring MVC to adapt controllers.

Are you familiar with spring transactions, and generally which implementation you use

  • Programmatic transactions, hard-coded in code. (Not recommended)
  • Declarative transactions, configured in configuration files (recommended)

Generally in our enterprise development process, we usually use declarative transactions, declarative transactions are divided into two types: one is based on XML, one is based on annotations, usually with annotations

What are some of the transaction propagation behaviors in Spring transactions?

Cases that support the current transaction:

  • TransactionDefinition. PROPAGATION_REQUIRED: if a transaction exists, then join the transaction; If there is no transaction currently, a new transaction is created.
  • TransactionDefinition. PROPAGATION_SUPPORTS: if a transaction exists, then join the transaction; If there is no transaction currently, it continues in a non-transactional manner.
  • TransactionDefinition. PROPAGATION_MANDATORY: if a transaction exists, then join the transaction; If there is no transaction currently, an exception is thrown. (Mandatory: mandatory)

The current transaction is not supported:

  • TransactionDefinition. PROPAGATION_REQUIRES_NEW: create a new transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NOT_SUPPORTED: run way of transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NEVER: run way of transaction, if the current transaction, throw an exception.

What’s the difference between a BeanFactory and a FactoryBean?

  • BeanFactory is an IOC container or object Factory. In Spring, all beans are managed by the BeanFactory(IOC container), which provides the ability to instantiate and fetch objects.
  • A FactoryBean is a Bean. This Bean is not a simple Bean, but a FactoryBean that produces or decorates the generation of objects. Its implementation is similar to the factory and decorator patterns in the design pattern.

Let’s talk about Spring’s loop dependencies

  • Spring’s cyclic dependency means that two classes automatically inject each other via @AutoWired. That is, class A contains A reference to an object of class B and needs to be injected automatically, while class B contains A reference to an object of class A and needs to be injected automatically.
  • For cyclic dependency problem, Spring adopts different treatment strategies according to different injection methods. If both parties use property value injection or setter method injection, Spring can automatically solve the problem of cyclic dependency injection and the application can be successfully started. If both parties use constructors to inject each other or the main bean object (the bean object that Spring loads first during startup), Spring cannot solve cyclic dependency injection and the program fails to start.

First, Spring supports circular references by default in the singleton case; Two bean dependencies can be successfully initialized without any configuration; Spring source code in the creation of the bean when the first to create the bean object, after the creation of the object by judging the container object allowCircularReferences attribute to determine whether to allow the cache of the temporary object, if the cache can be successful through the cache to expose the temporary object to complete the cycle dependence; This property defaults to true, so spring supports loop dependency by default. However, spring provides an API for programmers to modify this property, so spring also provides the ability to turn off loop references.

How does Spring deal with circular references

First, Spring maintains three maps internally, which is commonly referred to as a level 3 cache.

The author looked through the Spring documentation but did not find the concept of three-level cache, which is probably a local term for ease of understanding.

In the Spring of DefaultSingletonBeanRegistry class, you will suddenly found that the three Map was hanging over class:

  • SingletonObjects is our most familiar friend, commonly known as “singleton pool” or “container”, the cache where the singleton Bean is created and completed.
  • The singletonFactories map creates the original factory of the Bean
  • EarlySingletonObjects is an early reference to a mapping Bean, meaning that the Bean in the Map is not complete or even called a “Bean”, just an Instance.

The last two maps are actually “stepping-stone” level maps that are used for Bean creation and then removed.

That’s why I was confused by the term “level 3 Cache” in my previous post, probably because comments start with Cache of.

Why become the last two maps as stepping stones, assuming that the Bean that ends up in singletonObjects is the cup of “cool white” you want.

So Spring prepared two singletonFactories and earlySingletonObjects, and put the hot water into singletonObjects.

Different scenarios for circular references, and what methods can be used to solve circular references

Why do some injection methods fail to solve circular dependencies? The source code shows that they don’t use the earlySingletonObjects cache, so they can’t solve the loop dependency

Some ways to address loop dependencies that Spring cannot

If a cyclic dependency problem occurs in the project, it indicates that spring cannot resolve the cyclic dependency problem by default. It depends on the type of cyclic dependency of the project’s print log. Currently, the following situations are involved:

This type of circular dependency problem can be solved by many methods, including:

  • Use the @lazy annotation to lazily load
  • Specify the loading sequence using the @dependson annotation
  • Change the file name to change the loading order of loop dependent classes

What is Mybatis?

  • Mybatis is a semi-ORM (Object relational Mapping) framework, which internally encapsulates JDBC, loading drivers, creating connections, creating statements and other complex processes. Developers only need to pay attention to how to write SQL statements during development, which can strictly control SQL execution performance and achieve high flexibility.
  • As a semi-ORM framework, MyBatis can configure and map native information using XML or annotations, mapping POJOs to records in the database, avoiding almost all JDBC code and manually setting parameters and fetching result sets.

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

  • #{} is precompiled processing, and ${} is string substitution.
  • Mybatis will replace #{} with? Call the set method in PreparedStatement to assign the value.
  • When Mybatis processes, it is to replace {} with the value of a variable.
  • Using #{} can effectively prevent SQL injection and improve system security.

Mybatis level 1 cache and level 2 cache

Level 1 cache transaction scope: The cache can only be accessed by the current transaction. The lifetime of the cache depends on the lifetime of the transaction. When the transaction ends, the lifetime of the cache ends. In this scope, the cache medium is memory. Level 2 cache process scope: The cache is shared by all transactions within the process. These transactions may be concurrent access to the cache, so the necessary transaction isolation mechanisms must be applied to the cache. The lifetime of the cache depends on the lifetime of the process, and the lifetime of the cache ends when the process terminates. Process-wide caches can hold large amounts of data, so they can be stored in memory or on hard disk.

Let’s talk about the overall architecture of Mybatis

In fact, I think myBatis framework needs to do the main things we know, why? Because in fact, if we do not have Mybatis we can also do database operation, right, that is JDBC operation, that in fact, Mybatis is encapsulated in JDBC on a framework, it needs to do is so much, LET me summarize

  • The first is the basics of connection management, transaction management, configuration loading, and cache handling
  • And then the core functions, our parameter mapping, our SQL parsing, our SQL execution, our result mapping
  • On top of that, it encapsulates our unified CRUD interface, and that’s it.

The above is the whole thing mybatis to do, of course, each piece of function processing is not so simple.

Mybatis source familiar with it, find you familiar with the place to chat

The figure above is a core process of the whole Mybatis. In fact, no matter spring or MyBatis, all frameworks can be divided into two parts. One is the initialization process, which is equivalent to the process of receiving customers by making preparations; the second is the actual receiving process. So no matter which frame source is so, Mybatis is certainly no exception

  • Initialization process

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

The core of mybatis lies in SqlSessionFactory. First, SqlSessionFactory build involves parsing various configuration files. The first one to parse is Configuration, which has many tags. You have a properties node, you have a mapper node, you can find our mapper.xml and then you can parse the node, report various cach,select, etc., and then you parse the XML and bind it to our mapper interface through the namespace, Generate code objects and put them in konwsmapper. Finally, you can generate this SqlSessionFactory

  • The actual execution process

Is when our mybatis is ready? Sqlsession. GetMapper, which is also the proxy object, and then pull it to MapperMethod, SqlSession then forwards the query method to Executor. Executor accesses the database for data based on JDBC. Executor uses reflection to convert the data into a POJO and return it to SqlSession. Returns the data to the caller.

The end of the

Let’s take a look at the components of SpringBoot and SpringCloud

Daily for praise

Ok, everybody, that’s all for this article, you can see people here, they are real fans.

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article

Wechat search “six pulse Excalibur program life” reply 888 I find a lot of information to you