The system knowledge points and interview questions of Java learning summarized by myself have been opened source and have been 41K + Star at present. Suggestions and guidance are welcome, as well as Star: github.com/Snailclimb/…

This article is mainly intended to deepen your understanding of Spring through some questions, so it won’t involve too much code! It took me a long time to sort out this article. I did not pay attention to many of the following problems when USING Spring. I also consulted many materials and books temporarily to make up the problems. There are also a lot of articles on Spring FAQ/interview questions, I feel that most of them are copied from each other, and many of the questions are not very sweaty, and some of the answers are problematic. So, I spent a week of spare time to sort it out, hoping to be helpful to everyone.

What is the Spring Framework?

Spring is a lightweight development framework designed to improve developer productivity and system maintainability. Spring official website: spring. IO /.

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.

The Spring website lists six features of Spring:

  • Core technologies: Dependency Injection (DI), AOP, Events, Resources, I18N, validation, data binding, type conversion, SpEL.
  • Testing: Mock objects, TestContext framework, Spring MVC tests, WebTestClient.
  • Data access: transaction, DAO support, JDBC, ORM, marshalling XML.
  • Web support: Spring MVC and Spring WebFlux Web Framework.
  • Integration: remote processing, JMS, JCA, JMX, email, tasks, scheduling, caching.
  • Languages: Kotlin, Groovy, dynamic languages.

Name some important Spring modules?

The figure below corresponds to the Spring4.x release. In the current 5.x release, the Portlet component of the Web module has been deprecated and a WebFlux component for asynchronous responsive processing has been added.

  • Spring Core: Basic, it can be said that all of Spring’s other functions depend on this library. It mainly provides IOC dependency injection function.
  • **Spring Aspects ** : This module supports integration with AspectJ.
  • Spring AOP: Provides aspect-oriented programming implementations.
  • Spring JDBC: Java database connection.
  • Spring JMS: Java messaging service.
  • Spring ORM: Used to support ORM tools such as Hibernate.
  • Spring Web: Provides support for creating Web applications.
  • Spring Test: Provides support for JUnit and TestNG tests.

Talk about your understanding of Spring IoC and AOP

IoC

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 unique to Spirng. 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.

In the Spring era, we used to configure beans in XML files, but later developers decided that XML files were not a good way to configure beans, so SpringBoot annotation configuration slowly became popular.

Recommended reading: www.zhihu.com/question/23…

The Spring IOC initialization process:

IOC source code reading

  • Javadoop.com/post/spring…

AOP

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. Spring AOP will use Cglib to generate a subclass of the proxied object as the proxy, as shown in the following figure:

You can also use AspectJ, which is already integrated with Spring AOP and is arguably 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 is the difference between Spring AOP and AspectJ AOP?

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,

If we have fewer cuts, there is not much difference in performance. However, when there are too many facets, AspectJ is the best choice, which is much faster than Spring AOP.

What are the scopes of beans in Spring?

  • Singleton: A unique bean instance. Beans in Spring are singleton by default.
  • Prototype: Each request creates a new bean instance.
  • Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.
  • Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.
  • Global-session: the global session scope, which is only meaningful in portlet-based web applications, is no longer available in Spring5. Portlets are small Java Web plug-ins that can generate snippets of semantic code, such as HTML. They are based on portlet containers and can handle HTTP requests like servlets. However, unlike servlets, each portlet has a different session

Do you understand the thread-safety issues of singleton beans in Spring?

Most of the time we don’t use multithreading in our systems, so few people pay attention to it. Singleton beans have threading problems, mainly because of thread-safe writes to non-static member variables of an object when multiple threads are working on the same object.

There are two common solutions:

  1. Try to avoid defining mutable member variables in Bean objects (impractical).

  2. Define a ThreadLocal member variable in the class, and store the required variable member variables in the ThreadLocal (the recommended approach).

Bean life cycle in Spring?

This part has many articles online spoke, since the following arrangement: yemengying.com/2016/07/14/… , in addition to this article, and then recommend a good article: www.cnblogs.com/zrtqsk/p/37… .

  • The Bean container finds the definition of the Spring Bean in the configuration file.
  • The Bean container creates an instance of a Bean using the Java Reflection API.
  • If some attribute values are involved utilizeset()Method sets some property values.
  • If the Bean is implementedBeanNameAwareInterface, callsetBeanName()Method, the name of the Bean passed in.
  • If the Bean is implementedBeanClassLoaderAwareInterface, callsetBeanClassLoader()Method, passed inClassLoaderObject.
  • If the Bean is implementedBeanFactoryAwareInterface, callsetBeanClassLoader()Method, passed inClassLoadeR object instance.
  • Similar to the above, if other implementations are implemented*.AwareInterface to invoke the corresponding method.
  • If there is a Spring container associated with loading the BeanBeanPostProcessorObject, executepostProcessBeforeInitialization()methods
  • If the Bean is implementedInitializingBeanInterface, executeafterPropertiesSet()Methods.
  • If the Bean definition in the configuration file contains the init-method attribute, the specified method is executed.
  • If there is a Spring container associated with loading the BeanBeanPostProcessorObject, executepostProcessAfterInitialization()methods
  • When it is time to destroy the Bean, if the Bean is implementedDisposableBeanInterface, executedestroy()Methods.
  • When it is time to destroy a Bean, execute the specified method if the Bean’s definition in the configuration file contains the destroy-method attribute.

Here is:

A Chinese version of a similar version:

What do you know about Spring MVC?

Talking about this issue, we have to mention the previous Model1 and Model2 era without Spring MVC.

  • Model1 era: Many people who learn Java backend later may not have been exposed to JavaWeb application development in Model1 mode. In Model1 mode, the whole Web application is almost composed of JSP pages, only a small amount of JavaBean to deal with database connection, access and other operations. In this mode, JSP is both the control layer and the presentation layer. Clearly, there are many problems with this model. (1) Mixing control logic and presentation logic leads to very low code reuse rate; (2) The front end and back end depend on each other, it is difficult to test and the development efficiency is very low;
  • Model2 time: Those who have learned Servlet and done relevant Demo should understand the development mode of “Java Bean(Model)+ JSP (View,)+ Servlet (Controller)”, which is the early JavaWeb MVC development mode. Model: Data involved in the system, namely DAOs and beans. View: Shows the data in the model, just for presentation. Controller: Handles all user requests sent to, returns data to the JSP and presents it to the user.

There are still many problems in Model2 mode. The degree of abstraction and encapsulation of Model2 is far from enough. When developing with Model2, it is inevitable to repeat the wheel, which greatly reduces the maintainability and reusability of the program. As a result, many MVC frameworks related to JavaWeb development have been developed, such as Struts2, but Struts2 is cumbersome. With the popularity of Spring lightweight development frameworks, Spring MVC framework emerged in the Spring ecosystem, and Spring MVC is the best MVC framework currently available. Compared to Struts2, Spring MVC is simpler and more convenient to use, more efficient to develop, and faster to run.

MVC is a design pattern, and Spring MVC is an excellent MVC framework. Spring MVC can help us develop a cleaner Web layer, and it is inherently integrated with the Spring framework. Under Spring MVC, we generally divide back-end projects into Service layer (processing business), Dao layer (database operation), Entity layer (Entity class), and Controller layer (control layer, returning data to the front page).

A simple schematic of Spring MVC looks like this:

Do you know how SpringMVC works?

The principle is shown in the figure below:

Here’s a bit of a typo: Spring MVC’s entry function, the front-end controller DispatcherServlet, is used to receive requests and respond to results.

Process Description (Important) :

  1. The client (browser) sends the request, directly toDispatcherServlet.
  2. DispatcherServletCalled based on the request informationHandlerMappingParse the request corresponding toHandler.
  3. Parse to the correspondingHandlerThat’s what we sayControllerController) after starting fromHandlerAdapterAdapter processing.
  4. HandlerAdapterDepending on theHandlerTo call the real handler to open the request and process the corresponding business logic.
  5. When the processor finishes processing the business, it returns oneModelAndViewObject,ModelIs the returned data object,ViewIt’s a logical oneView.
  6. ViewResolverWill follow logicViewFind the actualView.
  7. DispaterServletThe return ofModelTo pass toViewView rendering.
  8. theViewReturn to the requester (browser)

What design patterns are used in the Spring framework?

For a more detailed description of some of the following design patterns, see Pen’s original post, interviewer: “What design patterns are used in Spring?” .

  • Factory design pattern: Spring uses factory mode to passBeanFactory,ApplicationContextCreate the bean object.
  • Proxy design pattern: Implementation of Spring AOP functionality.
  • Singleton design pattern: Beans in Spring are singleton by default.
  • Template method pattern: in the SpringjdbcTemplate,hibernateTemplateClasses that operate on databases that end in Template use the Template pattern.
  • Wrapper design pattern: Our project needs to connect to multiple databases, and different customers need to access different databases on each visit. This pattern allows us to dynamically switch between different data sources based on customer needs.
  • Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern.
  • Adapter modeThe adaptor pattern is used in Spring AOP enhancements or Advice, and adaptor pattern adaptation is used in Spring MVCController.
  • .

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

  1. Different objects:@ComponentAnnotations apply to classes, and@BeanAnnotations apply to methods.
  2. @ComponentIt is usually automatically detected by classpath scanning and automatically assembled into the Spring container (we can use it@ComponentScanThe annotation defines the path to scan for classes that identify the assembly to be automatically assembled into Spring’s bean container.@BeanAn annotation is usually defined to produce the bean in a method marked with the annotation,@BeanTells Spring that this is an example of a class and gives it back to me when I need to use it.
  3. @BeanAnnotations thanComponentAnnotations are more customizable, and there are many places we can only pass@BeanAnnotations to register beans. For example, when we reference a third party library class that needs to be assembled intoSpringContainer, can only pass through@BeanTo implement.

Example use of @bean annotations:

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService(a) {
        return newTransferServiceImpl(); }}Copy the code

The above code is equivalent to the following XML configuration

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>
Copy the code

The following example cannot be implemented with @Component.

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return newserviceImpl3(); }}Copy the code

What are the annotations that declare a class as a Spring bean?

We typically use @AutoWired annotation auto-assembly beans. To identify a class as a class that can be used with @AutoWired annotation auto-assembly beans, use the following annotations:

  • @Component: generic annotation that can mark any class asSpringComponents. This can be used if a Bean does not know it belongs to a layer@ComponentAnnotation annotation.
  • @Repository: Corresponds to the Dao layer, which is mainly used for database operations.
  • @Service: Corresponds to the service layer, which mainly involves some complex logic and requires the Dao layer.
  • @Controller: Corresponding to the Spring MVC control layer, the primary user accepts the user request and calls the Service layer to return data to the front-end page.

How many ways does Spring manage transactions?

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

Declarative transactions fall into two categories:

  1. Declarative TRANSACTIONS based on XML
  2. Annotation-based declarative transactions

What are the isolation levels in Spring transactions?

Five constants representing the isolation level are defined in the TransactionDefinition interface:

  • TransactionDefinition. ISOLATION_DEFAULT: use a backend database default isolation level, Mysql default REPEATABLE_READ isolation level used Oracle READ_COMMITTED) isolation level used by default.
  • TransactionDefinition. ISOLATION_READ_UNCOMMITTED: the lowest isolation level, allowing the read has not yet been submitted data changes, may lead to dirty reads, phantom read or not repeatable read
  • TransactionDefinition. ISOLATION_READ_COMMITTED: allow read of concurrent transactions have to submit data, can prevent dirty reads, but phantom read or not repeatable read could still happen
  • TransactionDefinition. ISOLATION_REPEATABLE_READ: many of the same field to read the results are consistent, unless the data have been modified by itself affairs on their own, can prevent the dirty read and not repeatable read, but phantom read could still happen.
  • TransactionDefinition. ISOLATION_SERIALIZABLE: the highest isolation level, completely obey the ACID isolation level. All transactions are executed one by one so that interference between transactions is completely impossible. That is, this level prevents dirty reads, unrepeatable reads, and phantom reads. But this severely affects the performance of the program. This level is also not typically used.

What kinds of transaction propagation behavior do Spring transactions have?

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.

Other information:

  • TransactionDefinition. PROPAGATION_NESTED: if a transaction exists, then create a transaction for the current affairs of nested transactions to run; If no current affairs, the value of equivalent to the TransactionDefinition. PROPAGATION_REQUIRED.

reference

  • Inside Spring Technology
  • www.cnblogs.com/wmyskxz/p/8…
  • www.journaldev.com/2696/spring…
  • www.edureka.co/blog/interv…
  • Howtodoinjava.com/interview-q…
  • www.tomaszezula.com/2014/02/09/…
  • Stackoverflow.com/questions/3…

The public,

If you want to follow my updated articles and shared dry goods in real time, you can follow my official account.

“Java interview assault “: derived from this document designed for the interview and born of the “Java interview assault” V2.0 PDF version of the public number background reply “Java interview assault “can be free!

Necessary learning resources for Java engineers: Some Java engineers commonly use learning resources public account background reply keyword “1” can be free of routine access.