Summary of Spring common interview questions (super detailed answer reprinted)

Original link: https://blog.csdn.net/a745233700/article/details/80959716

1. What is Spring?

        Spring is a lightweight IoC and AOP container framework. It is a framework that provides basic services for Java applications. The purpose is to simplify the development of enterprise applications. It allows developers to only care about business needs. There are three common configuration methods: XML-based configuration, annotation-based configuration, and Java-based configuration.

It is mainly composed of the following modules:

Spring Core: core class library, providing IOC services;

Spring Context: Provides framework-style Bean access methods and enterprise-level functions (JNDI, timed tasks, etc.);

Spring AOP: AOP service;

Spring DAO: Abstraction of JDBC, which simplifies the handling of data access exceptions;

Spring ORM: support for the existing ORM framework;

Spring Web: Provides basic Web-oriented comprehensive features, such as multi-party file upload;

Spring MVC: Provide Model-View-Controller implementation for Web applications.

 

2. What are the advantages of Spring?

(1) Spring is a low-intrusive design, with extremely low code pollution;

(2) Spring's DI mechanism transfers the dependencies between objects to the framework for processing, reducing the coupling of components;

(3) Spring provides AOP technology to support centralized management of some common tasks, such as security, transactions, logs, permissions, etc., to provide better reuse.

(4) Spring provides integrated support for mainstream application frameworks.

 

3. Spring's AOP understanding:

OOP is object-oriented, allowing developers to define vertical relationships, but is not suitable for defining horizontal relationships, which leads to a lot of code duplication, which is not conducive to the reuse of various modules.

AOP, generally called aspect-oriented, as a supplement to object-oriented, is used to extract and encapsulate common behaviors and logic that have nothing to do with the business but affect multiple objects into a reusable module, this module Named "Aspect", it reduces the repetitive code in the system, reduces the coupling between modules, and improves the maintainability of the system. It can be used for authority authentication, log, and transaction processing.

The key to the realization of AOP lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy. The representative of static proxy is AspectJ; the representative of dynamic proxy is Spring AOP.

(1) AspectJ is an enhancement of static proxy. The so-called static proxy means that the AOP framework will generate AOP proxy classes during the compilation phase, so it is also called compile-time enhancement. It will weave AspectJ (aspects) into Java bytes during the compilation phase In the code, it is the enhanced AOP object when it runs.

(2) The dynamic proxy used by Spring AOP. The so-called dynamic proxy means that the AOP framework does not modify the bytecode, but temporarily generates an AOP object for the method in memory each time it runs. This AOP object contains the target object. All methods of, and enhanced processing at a specific point of contact, and callback methods of the original object.

There are two main ways of dynamic proxy in Spring AOP, JDK dynamic proxy and CGLIB dynamic proxy:

        ① JDK dynamic proxy only provides interface proxy, and does not support class proxy. The core InvocationHandler interface and Proxy class. InvocationHandler invokes the code in the target class through the invoke() method reflection, dynamically weaving the crosscutting logic and business together; then, Proxy uses InvocationHandler to dynamically create an instance that conforms to a certain interface, Generate a proxy object of the target class.

        ② If the proxy class does not implement the InvocationHandler interface, Spring AOP will choose to use CGLIB to dynamically proxy the target class. CGLIB (Code Generation Library) is a class library for code generation, which can dynamically generate a subclass object of a specified class at runtime, and cover specific methods and add enhanced code to achieve AOP. CGLIB is a dynamic proxy through inheritance, so if a class is marked as final, it cannot use CGLIB as a dynamic proxy.

(3) The difference between static proxy and dynamic proxy is that the timing of generating AOP proxy objects is different. Relatively speaking, the static proxy method of AspectJ has better performance, but AspectJ requires a specific compiler for processing, while Spring AOP does not require specific compilation器处理。 Processing.

 InvocationHandler's invoke(Object proxy,Method method,Object[] args): proxy is the finally generated proxy instance; method is a specific method of the proxy target instance; args is the specific input parameters of a method of the proxy target instance, Used when the method is called by reflection.

 

4. Spring's IoC understanding:

(1) IOC is the inversion of control, which refers to the transfer of the control right to create the object. The initiative and timing of the creation of the object was previously controlled by itself, but now this power is transferred to the Spring container, and the container is configured according to the configuration Files are used to create instances and manage the dependencies between each instance. The loose coupling between objects is also conducive to the reuse of functions. DI dependency injection and inversion of control are descriptions of the same concept from different perspectives, that is, the application relies on the IoC container to dynamically inject the external resources needed by the object at runtime.

(2) The most intuitive expression is that IOC allows the creation of objects without having to go to new, and can be automatically produced by spring, using the reflection mechanism of java, dynamically creating and managing objects according to configuration files at runtime, and calling the objects Method.

(3) Spring's IOC has three injection methods: constructor injection, setter method injection, and annotation injection.

IoC keeps cooperating components loosely coupled, while AOP programming allows you to separate the functions that are spread across all layers of the application to form reusable functional components.

 

5. What is the difference between BeanFactory and ApplicationContext?

        BeanFactory and ApplicationContext are the two core interfaces of Spring, and both can be used as Spring containers. The ApplicationContext is a sub-interface of BeanFactory.

(1) BeanFactory: It is the lowest-level interface in Spring. It contains definitions of various Beans, reads bean configuration documents, manages bean loading and instantiation, controls bean life cycle, and maintains dependencies between beans. As a derivation of BeanFactory, ApplicationContext interface not only provides the functions of BeanFactory, but also provides more complete framework functions:

①Inherit MessageSource, so it supports internationalization.

②Uniform access to resource files.

③Provide events to register beans in the listener.

④ Load multiple configuration files at the same time.

⑤ Load multiple (inherited) contexts so that each context focuses on a specific level, such as the web layer of the application.

(2) BeanFactroy uses lazy loading to inject Beans, that is, only when a Bean is used (call getBean()), the Bean is loaded and instantiated. In this way, we cannot find some existing Spring configuration problems. If a certain attribute of Bean is not injected, after BeanFacotry is loaded, an exception will not be thrown until the first use of the getBean method.

        ② ApplicationContext, which creates all Beans at once when the container is started. In this way, when the container starts, we can find configuration errors in Spring, which helps to check whether the dependent properties are injected. After ApplicationContext starts, all single-instance beans are pre-loaded. By pre-loading single-instance beans, you can ensure that when you need them, you don't have to wait because they have been created.

        ③Compared with the basic BeanFactory, the only disadvantage of ApplicationContext is memory space. When there are more Beans in the application, the startup of the program is slower.

(3) BeanFactory is usually created programmatically, ApplicationContext can also be created in a declarative way, such as using ContextLoader.

(4) Both BeanFactory and ApplicationContext support the use of BeanPostProcessor and BeanFactoryPostProcessor, but the difference between the two is: BeanFactory requires manual registration, while ApplicationContext is automatically registered.

 

6. Please explain the life cycle of Spring Bean?

 Let me first talk about the life cycle of Servlet: instantiation, initial init, receiving request service, destroying destroy;

 The life cycle of the Bean in the Spring context is similar, as follows:

(1) Instantiate Bean:

For the BeanFactory container, when a client requests an uninitialized bean from the container, or needs to inject another uninitialized dependency when initializing the bean, the container will call createBean for instantiation. For the ApplicationContext container, when the container is started, all beans are instantiated by obtaining the information in the BeanDefinition object.

(2) Set object properties (dependency injection):

The instantiated object is encapsulated in the BeanWrapper object. Then, Spring completes dependency injection based on the information in the BeanDefinition and the attribute setting interface provided by the BeanWrapper.

(3) Processing the Aware interface:

Next, Spring will detect whether the object implements the xxxAware interface, and inject the relevant xxxAware instance into the Bean:

① If this Bean has implemented the BeanNameAware interface, the setBeanName(String beanId) method implemented by it will be called, and what is passed here is the id value of the Bean in the Spring configuration file;

② If this Bean has implemented the BeanFactoryAware interface, the setBeanFactory() method implemented by it will be called, passing the Spring factory itself.

③If the Bean has implemented the ApplicationContextAware interface, it will call the setApplicationContext(ApplicationContext) method and pass in the Spring context;

(4)BeanPostProcessor:

If you want to perform some custom processing on the Bean, you can make the Bean implement the BeanPostProcessor interface, which will call the postProcessBeforeInitialization(Object obj, String s) method.

(5)InitializingBean 与 init-method:

If the bean is configured with the init-method attribute in the Spring configuration file, its configured initialization method will be automatically called.

(6) If the Bean implements the BeanPostProcessor interface, the postProcessAfterInitialization(Object obj, String s) method will be called; since this method is called at the end of Bean initialization, it can be applied to memory or caching technology;

After the above steps are completed, the Bean has been created correctly, and then the Bean can be used.

(7) DisposableBean :

When the Bean is no longer needed, it will go through the cleaning phase. If the Bean implements the DisposableBean interface, it will call its implemented destroy() method;

(8)destroy-method:

Finally, if the destroy-method attribute is configured in the Spring configuration of this Bean, its configured destruction method will be called automatically.

 

7. Explain the scope of several beans supported by Spring.

The beans in the Spring container can be divided into 5 ranges:

(1) Singleton: By default, there is only one bean instance in each container, and the singleton mode is maintained by BeanFactory itself.

(2) Prototype: Provide an instance for each bean request.

(3) request: Create an instance for each network request. After the request is completed, the bean will be invalidated and recycled by the garbage collector.

(4) Session: Similar to the request scope, ensure that there is an instance of a bean in each session. After the session expires, the bean will become invalid.

(5) global-session: global scope, global-session is related to portlet applications. When your application is deployed to work in a portlet container, it contains many portlets. If you want to declare that all portlets share global storage variables, then the global variables need to be stored in global-session. The global scope has the same effect as the session scope in Servlet.

 

8. Are singleton beans in the Spring framework thread-safe?

        The Spring framework does not perform any multi-threaded encapsulation of singleton beans. The thread safety and concurrency issues of singleton beans need to be solved by the developer. But in fact, most Spring beans do not have mutable states (such as Serview and DAO classes), so to some extent, Spring singleton beans are thread-safe. If your bean has multiple states (such as View Model objects), you need to ensure thread safety yourself. The most obvious solution is to change the scope of polymorphic beans from "singleton" to "prototype".

9. How does Spring deal with thread concurrency?

In general, only stateless beans can be shared in a multithreaded environment. In Spring, most beans can be declared as singleton scope, because Spring uses ThreadLocal to handle non-thread-safe states in some beans. Solve thread safety issues.

ThreadLocal and thread synchronization mechanisms are both to solve the problem of access conflicts of the same variables in multiple threads. The synchronization mechanism adopts the "time for space" approach, and only provides one variable. Different threads need to acquire locks before accessing, and threads that have not acquired locks need to be queued. And ThreadLocal uses the "space for time" approach.

ThreadLocal will provide an independent variable copy for each thread, thereby isolating the data access conflicts of multiple threads. Because each thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe shared objects. When writing multi-threaded code, unsafe variables can be encapsulated in ThreadLocal.

 

10-1, Spring has several ways to inject beans based on xml:

(1) Set method injection;

(2) Constructor injection: ①Set the position of the parameter through index; ②Set the parameter type through type;

(3) Static factory injection;

(4) Example factory;

Details can be read: https://blog.csdn.net/a745233700/article/details/89307518

10-2, Spring's automatic assembly:

In spring, an object does not need to find or create other objects associated with it by itself. The container is responsible for assigning references to objects that need to cooperate with each other, and autowire is used to configure the automatic loading mode.

There are 5 kinds of automatic assembly in the Spring framework xml configuration:

(1) no: The default method is not to perform automatic assembly, and the bean is assembled by manually setting the ref attribute.

(2) byName: Automatic assembly is carried out through the name of the bean. If the property of one bean is the same as the name of another bean, automatic assembly is carried out. 

(3) byType: Automatic assembly through the data type of the parameter.

(4) Constructor: Use the constructor to assemble, and the parameters of the constructor are assembled through byType.

(5) autodetect: automatic detection, if there is a construction method, it is automatically assembled by construct, otherwise it is automatically assembled by byType.

Annotation-based method:

Use the @Autowired annotation to automatically assemble the specified bean. Before using @Autowired annotation, you need to configure it in the Spring configuration file, <context:annotation-config />. When spring IoC is started, the container automatically loads an AutowiredAnnotationBeanPostProcessor post processor. When the container scans for @Autowied, @Resource, or @Inject, it will automatically find the required bean in the IoC container and assemble it to the properties of the object. When using @Autowired, first query the corresponding type of bean in the container:

If the query result is exactly one, the bean is assembled to the data specified by @Autowired;

If there is more than one result of the query, @Autowired will search by name;

If the result of the above search is empty, an exception will be thrown. When solving, use required=false.

@Autowired can be used for: constructor, member variable, Setter method

Note: The difference between @Autowired and @Resource

(1) @Autowired is injected by type assembly by default. By default, it requires dependent objects to exist (you can set its required attribute to false).

(2) @Resource assembles injection according to the name by default. Only when no bean matching the name can be found, the injection is assembled according to the type.

 

11. What design patterns are used in the Spring framework?

(1) Factory model: BeanFactory is the embodiment of the simple factory model, used to create instances of objects;

(2) Singleton mode: Bean defaults to singleton mode.

(3) Proxy mode: Spring’s AOP function uses JDK’s dynamic proxy and CGLIB bytecode generation technology;

(4) Template method: used to solve the problem of code duplication. For example. RestTemplate, JmsTemplate, JpaTemplate.

(5) Observer mode: Define a one-to-many dependency on object keys. When the state of an object changes, all objects that depend on it will be notified and updated by braking, such as the implementation of listener in Spring - ApplicationListener.

 

12. Implementation methods and principles of Spring transactions:

The essence of Spring transaction is actually the database's support for transactions. Without database transaction support, Spring cannot provide transaction functions. The real transaction commit and rollback of the database layer is achieved through binlog or redo log.

(1) Types of Spring transactions:

Spring supports programmatic transaction management and declarative transaction management in two ways:

① Programmatic transaction management uses TransactionTemplate.

② Declarative transaction management is based on AOP. Its essence is to intercept the method before and after the method through the AOP function, weave the transaction processing function into the interception method, that is, add a transaction before the target method starts, and submit or roll back the transaction according to the execution after the target method is executed. .

The biggest advantage of declarative transactions is that there is no need to add transaction management code to the business logic code. You only need to make relevant transaction rule declarations in the configuration file or through @Transactional annotations to apply transaction rules to business logic. in.

Declarative transaction management is better than programmatic transaction management. This is the non-intrusive development method advocated by Spring, so that business code is not polluted, and complete transaction support can be obtained by adding annotations. The only downside is that the finest granularity can only be applied to the method level, and cannot be applied to the code block level like a programmatic transaction.

(2) Spring's transaction propagation behavior:

The propagation behavior of spring transactions refers to the behavior of how spring handles these transactions when multiple transactions exist at the same time.

① PROPAGATION_REQUIRED: If there is no transaction currently, create a new transaction, if there is a transaction, join the transaction, this setting is the most commonly used setting.

② PROPAGATION_SUPPORTS: Support the current transaction. If there is a transaction, it will join the transaction. If there is no transaction, it will be executed as a non-transaction. '

③ PROPAGATION_MANDATORY: Support the current transaction. If there is a transaction, it will join the transaction. If there is no transaction, an exception will be thrown.

④ PROPAGATION_REQUIRES_NEW: Create a new transaction, regardless of whether there is currently a transaction, create a new transaction.

⑤ PROPAGATION_NOT_SUPPORTED: Perform operations in a non-transactional manner. If there is a transaction currently, the current transaction is suspended.

⑥ PROPAGATION_NEVER: Execute in a non-transactional manner. If there is a transaction currently, an exception is thrown.

⑦ PROPAGATION_NESTED: If a transaction currently exists, it will be executed in a nested transaction. If there is no transaction currently, it is executed according to the REQUIRED attribute.

(3) Isolation level in Spring:

① ISOLATION_DEFAULT: This is the default isolation level of PlatfromTransactionManager, using the default transaction isolation level of the database.

② ISOLATION_READ_UNCOMMITTED: Read uncommitted, allowing another transaction to see the uncommitted data of this transaction.

③ ISOLATION_READ_COMMITTED: Reading has been committed, ensuring that data modified by one transaction can be read by another transaction only after it is submitted, and the transaction's update to existing records can be seen.

④ ISOLATION_REPEATABLE_READ: Repeatable reading, ensuring that the data modified by one transaction can be read by another transaction after it is submitted, but the transaction's update to existing records cannot be seen.

⑤ ISOLATION_SERIALIZABLE: During the execution of a transaction, no updates to the database made by other transactions can be seen at all.

 

13. What are the different types of events in the Spring framework?

Spring provides the following 5 standard events:

(1) Context update event (ContextRefreshedEvent): It is triggered when the refresh() method in the ConfigurableApplicationContext interface is called.

(2) ContextStartedEvent: This event is triggered when the container calls the Start() method of ConfigurableApplicationContext to start/restart the container.

(3) ContextStoppedEvent: This event is triggered when the container calls the Stop() method of ConfigurableApplicationContext to stop the container.

(4) ContextClosedEvent: This event is triggered when the ApplicationContext is closed. When the container is closed, all singleton beans managed by it are destroyed.

(5) RequestHandledEvent: In a web application, this event is triggered when an http request (request) ends.

If a bean implements the ApplicationListener interface, the bean will automatically be notified when an ApplicationEvent is published.

 

14. Explain a few terms in Spring AOP:

(1) Aspect: The extracted common module may cross multiple objects. In Spring AOP, aspects can be implemented using common classes (pattern-based style) or @AspectJ annotations in common classes.

(2) Join point: refers to methods. In Spring AOP, a join point always represents the execution of a method. 

(3) Advice: An action performed on a specific join point of the aspect. There are various types of notifications, including notifications such as "around", "before", and "after". Many AOP frameworks, including Spring, use interceptors as the notification model and maintain a chain of interceptors centered on connection points.

(4) Pointcut: Pointcut refers to the definition of which Join points we want to intercept. Through the entry point expression, specify the interception method, such as specifying interception add*, search*.

(5) Introduction: (also known as inter-type declaration). Declare additional methods or fields of a certain type. Spring allows the introduction of new interfaces (and a corresponding implementation) to any object being proxied. For example, you can use an import to make the bean implement the IsModified interface to simplify the caching mechanism.

(6) Target Object: An object that is advised by one or more aspects. Some people call it an adviced object. Since Spring AOP is implemented through runtime proxy, this object is always a proxied object.

(7) Weaving: refers to the process of applying enhancements to the target object to create a new proxy object. Spring is weaving at runtime.

The concept of pointcut and join point matching is the key to AOP, which makes AOP different from other old technologies that only provide interception functions. The entry point makes the positioning advice (advice) independent of the OO level. For example, an around advice that provides declarative transaction management can be applied to a set of methods that span multiple objects (such as all business operations in the service layer).

15. What are the types of Spring notifications?

https://blog.csdn.net/qq_32331073/article/details/80596084

(1) Before advice: A notice executed before a join point, but this notice cannot prevent execution before the join point (unless it throws an exception).

(2) After returning advice: A notice executed after a join point is normally completed: for example, a method does not throw any exception and returns normally. 

(3) After throwing advice: the advice executed when the method exits by throwing an exception. 

(4) After (finally) advice: the notification executed when a connection point exits (regardless of normal return or abnormal exit). 

(5) Around Advice: An advice surrounding a join point, such as a method call. This is the most powerful type of notification. Surround notifications can complete custom behaviors before and after method calls. It also chooses whether to continue executing the connection points or directly return their own return value or throw an exception to end the execution. Surround notifications are the most commonly used type of notification. Most intercept-based AOP frameworks, such as Nanning and JBoss4, only provide surround notifications. 

The same aspect, the execution order of different advice:

①The execution sequence under no abnormal conditions:

around before advice
before advice
target method 执行
around after advice
after advice
afterReturning

②The execution sequence under abnormal conditions:

around before advice
before advice
target method execute
around after advice
after advice
afterThrowing: exception occurred
java.lang.RuntimeException: exception occurred

 

Related Reading:

Summary of SpringMVC common interview questions (super detailed answer)

Summary of Spring common interview questions (super detailed answer)

Summary of Mybatis common interview questions

Guess you like

Origin blog.csdn.net/qq_30764991/article/details/100936321