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 most of them are copied from each other, and many of the questions are not very good, some of the answers are also problematic. So, I spent a week of spare time to sort it out, hoping to be helpful to everyone.

1. 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.

2. List 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 provides support for integration with AspectJ.

  • Spring AOP: Provides a section-oriented programming implementation.

  • 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.

Core Container

Spring’s core container is the foundation upon which other modules are built, Spring-core, spring-beans, spring-context, spring-context-support, spring-expression (Spring expression language), etc.

Spring-core module: Provides the basic components of the framework, including Inversion of Control (IOC) and Dependency Injection (DI) capabilities.

Spring-beans module: Provides BeanFactory, a classic implementation of the factory pattern, where Spring calls managed objects beans.

The Spring-Context module builds on Core and Beans modules and provides a framework for accessing objects. It is a medium for accessing any object defined and configured. The ApplicationContext interface is the focus of the Context module.

Spring-context-support module: supports integration of third-party libraries into spring application contexts, especially for caching (EhCache, JCache) and task scheduling (CommonJ, Quartz) support.

Spring-expression module: provides a powerful expression language to support runtime query and manipulation of object diagrams. This is an extension of the Unified Expression Language (Unified EL) as specified in the JSP2.1 specification. The language supports setting and getting attribute values, attribute assignment, method calls, accessing the contents of arrays, collections, and indexers, logical and arithmetic operations, variable naming, and retrieving objects by name from Spring’s IOC container. It also supports list projection, selection, and common list aggregation.

Aspect Oriented Programming and Device Support (AOP)

It consists of three modules, spring-AOP, Spring-Aspects and Spring-Instrument.

Spring-aop module: Another core module of Spring that provides a faceted programming implementation that meets AOP requirements. As one of the most influential programming ideas after OOP (object-oriented programming), AOP has greatly expanded the way people think about programming. In Spring, based on dynamic proxy technology, you can define method interceptors and pointcuts to separate code by function for clean decoupling.

The Spring-Aspects module: provides integration with AspectJ, a powerful and mature AOP framework.

The Spring-Instrument module is a support module for AOP that provides Instrumentation support and class loaders for use in specific application servers. The main function is to generate a proxy class when the JVM is enabled, through which the programmer can modify the bytes of the class at run time, thus changing the function of a class and implementing AOP functions.

Data Access/Integeration

It consists of spring-JDBC, spring-ORM, spring-OXM, spring-JMS and spring-TX modules.

Spring-jdbc module: Provides a JDBC abstraction layer that simplifies JDBC by eliminating cumbersome JDBC coding and database vendor-specific error code parsing. It mainly provides JDBC template mode, relational database object mode, SimpleJdbc mode, transaction management to simplify JDBC programming. Main implementation class is JdbcTemplate, SimpleJdbcTemplate and NamedParameterJdbcTemplate.

Spring – the orm modules: ORM framework support module, mainly integrates Hibernate, Java Persistence API (JPA) and Java Data Objects (JDO) for resource management, Data access object (DAO) implementation and transaction strategy.

Spring – oxm module: Provides an abstraction layer to support OXM (OXM stands for object-to-XML-Mapping, which is an O/M-mapper that maps Java objects to XML data, or XML data to Java objects), for example: JAXB, Castor, XMLBeans, JiBX, XStream, and more.

Spring-jms module (Java Messaging Service) : Refers to the Java Messaging Service, which contains functions for producing and consuming messages. Since Spring4.1, integration with the Spring-Messaging module has been provided.

Spring-tx module: Transaction module that supports programmatic and declarative transaction management for implementing special interfaces and all POJO (plain Java object) classes.

Web

It consists of spring-Websocket, spring-WebMVC, Spring-Web, portlet and Spring-Webflux module.

Spring-websocket module: a new module added after Spring4.0, which implements duplex asynchronous communication protocol, implements WebSocket and SocketJS, and provides Socket communication and web push functions.

Spring-web MVC module: Also known as the Web-Servlet module, contains spring MVC and REST Web Services implementations for Web applications. The Spring MVC Framework provides a clear separation between domain model code and Web forms and integrates with all the other features of the Spring Framework.

Spring – the web module: It provides basic Web development integration functions, including initializing an IOC container and Web application context using Servlet listeners, classes for automatically loading WebApplicationContext features, Struts integration classes, file upload support classes, Filter classes, and a number of helper classes.

Portlet module: Implements aggregation of Web module functions, similar to functions of Servlet module, and provides MVC implementation in portlet environment.

The Spring-WebFlux module is a new non-blocking functional Web framework Reactive that can be used to build asynchronous, non-blocking, event-driven services that scale very well.

Messaging

The Spring-Messaging module.

Spring-messaging is a new module added from Spring4 that provides support for messaging architectures and protocols.

Test

The spring-test module.

The Spring-test module mainly supports testing. It supports unit testing and integration testing of Spring components using JUnit or TestNG.

Dependencies between Spring modules (JAR packages)

3. @RestController vs @Controller

ControllerReturn a page

Using @controller alone without @responseBody is usually used when you want to return a view, which is a more traditional Spring MVC application, corresponding to the case where the front and back end are not separated.

@RestControllerReturns JSON or XML data

However, @RestController returns only objects, and the object data is written directly to the HTTP Response in JSON or XML. This is a RESTful Web service, and it is the most common situation that daily development deals with today (the front and back ends are separated).

@Controller +@ResponseBodyReturns JSON or XML data

If you need to develop RESTful Web services prior to Spring4, you need to use @controller with the @responsebody annotation, So @controller + @responseBody = @restController (a new note added after Spring 4).

The @responseBody annotation converts the object returned by the Controller’s method to the specified format through the appropriate translator and writes it to the body of the HTTP Response object, which is usually used to return JSON or XML data. JSON data is often returned.

Reference:

  • Dzone.com/articles/sp… (Photo credit)
  • Javarevisited.blogspot.com/2017/08/dif…

4. Spring IOC & AOP

4.1 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 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.

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.

4.2 What are the differences 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.

5. Spring bean

5.1 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

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

There are safety concerns. This is because when multiple threads operate on the same object, writing to the object’s member variables is thread-safe.

However, in general, Controller, Service and Dao beans are stateless. Stateless beans cannot hold data and are therefore thread-safe.

There are two common solutions:

  1. Define one in the classThreadLocalMember variables, save the required variable member variables inThreadLocal(a recommended method).
  2. Change the scope of the Bean to “prototype” : a new Bean instance is created on each request, and there are naturally no thread-safety issues.

5.3 What is 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

5.4 What are the annotations for declaring 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 which layer it belongs to@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: Corresponds to the Spring MVC control layer, which is mainly used to accept user requests and call the Service layer to return data to the front-end page.

5.5 Bean life cycle in Spring?

This part has many articles online spoke, since the following arrangement: yemengying.com/2016/07/14/… (The original author may no longer maintain this blog, the connection is not accessible, can be accessed through its Github repository github.com/giraffe0813…) , 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.
  • 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:

6. Spring MVC

6.1 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, the 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 emerged, 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:

6.2 Do you know the working principle of SpringMVC?

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 theHandler To call the real handler to process the request and handle 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)

7. 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.
  • .

8. The Spring transaction

8.1 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

8.2 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.

8.3 What are 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.

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.

8.4@Transactional (rollbackFor = exception.class) annotation

We know: Exception is divided into run-time Exception RuntimeException and non-run-time Exception. Transaction management is critical to enterprise applications to ensure data consistency even if exceptions occur.

When the @Transactional annotation is applied to a class, all public methods of that class will have transaction attributes of that type. It can also be used at the method level to override class-level definitions. If a class or method adds this annotation, the method in the class throws an exception and is rolled back, as is the data in the database.

Without the rollbackFor attribute in the @Transactional annotation, transactions will rollback only when RuntimeException is encountered. The rollbackFor= exception.class annotation allows transactions to rollback when non-runtime exceptions are encountered.

Recommended reading for the @Transactional annotation:

  • Understand the use of @Transactional in Spring

9. JPA

9.1 How do I Use JPA to nonpersist a field in a Database?

Suppose we have the following class:

Entity(name="USER")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;
    
    @Column(name="USER_NAME")
    private String userName;
    
    @Column(name="PASSWORD")
    private String password;
  
    private String secrect;
  
}
Copy the code

What if we want the secrect field not to be persisted, not to be stored in the database? We can use the following methods:

static String transient1; // not persistent because of static
final String transient2 = “Satish”; // not persistent because of final
transient String transient3; // not persistent because of transient
@Transient
String transient4; // not persistent because of @Transient
Copy the code

Generally, the latter two methods are used more, and I personally use annotations more.

reference

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

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.