Interview questions-8Spring

What is IoC

IoC (Inversion of control) control inversion/inversion control. It is an idea, not a technical realization. Described is:
the creation and management of objects in the Java development domain.

For example: existing class A depends on class B

Traditional development method: often manually use the new keyword to new in class A. A B’s object comes out. The development method using IoC thinking: not
create objects through the new keyword, but through the IoC container (Spring framework) to help We instantiate the object. Which object we need, just go directly from the IoC container.
From the comparison of the above two development methods: we "lost a power"
(the power to create and manage objects), and thus also get a benefit (no need to consider the creation and management of objects, etc.)

Why is it called inversion of control

Control: refers to the right to create (instantiate, manage) objects

Reversal: control is given to the external environment (Spring framework, IoC container)

Insert picture description here

What problem does IoC solve

The degree of coupling or dependence between objects is reduced; resources become easier to manage; for example, you can easily implement a singleton if provided by the Spring container. For example: an existing
operation for User is developed using the two-tier structure of Service and Dao

Without using the IoC idea, if the Service layer wants to use the specific implementation of the Dao layer, it needs
to manually new the specific implementation class UserDaoImpl of IUserDao in UserServiceImpl through the new keyword (not directly new
interface class).

Insert picture description here

It's perfect, this method is also achievable, but we imagine the following scenario:

Suddenly received a new requirement during the development process, and developed another specific implementation class for the IUserDao interface. Because the Server
layer relies on the specific implementation of IUserDao, we need to modify the new
object in UserServiceImpl . If there is only one class that references the specific implementation of IUserDao, it may feel okay, and the modification is not very laborious, but if there are many places where the specific implementation of IUserDao is referenced, once
the implementation of IUserDao needs to be changed , then It will be a headache to modify.

Insert picture description here

Using the idea of ​​IoC, we transfer the control (creation, management) of the object to the IoC container for management, and we can directly "request" it from the IoC container when we use it.

Insert picture description here

IoC and DI don't be so stupid to distinguish that
IoC (Inverse of Control) is a design idea
or a certain pattern. This design idea is to hand over the control of objects created manually in the program to the Spring framework to manage. IoC is also used in other languages ​​and is not
unique to Spring. The IoC container is the carrier used by Spring to implement IoC. The IoC container is actually a Map (key, value), and
various objects are stored in the Map . The most common and reasonable implementation of IoC is called Dependency Injection (DI).

What is AOP

AOP: Aspect oriented programming, AOP is a continuation of OOP (object-oriented programming).

Let's first look at an OOP example.

For example: There are currently three classes, Horse, Pig, Dog, and all three classes have two methods, eat and run.

Through inheritance in OOP thinking, we can extract a parent class of Animal, and then put the eat and run
methods into the parent class. Horse, Pig, and Dog can automatically obtain the eat() and run() methods by inheriting the Animal class . This will reduce a lot of repetitive code.

Insert picture description here

OOP programming ideas can solve most of the code duplication problems. But there are some problems that cannot be dealt with. For example, if
duplicate code appears in the same position of multiple methods in the parent class Animal , OOP cannot solve it.

/**
 * 动物父类
 */
public class Animal {
    
    

    /** 身高 */
    private String height;

    /** 体重 */
    private double weight;

    public void eat() {
    
    
        // 性能监控代码
        long start = System.currentTimeMillis();

        // 业务逻辑代码
        System.out.println("I can eat...");

        // 性能监控代码
        System.out.println("执行时长:" + (System.currentTimeMillis() - start)/1000f + "s");
    }

    public void run() {
    
    
        // 性能监控代码
        long start = System.currentTimeMillis();

        // 业务逻辑代码
        System.out.println("I can run...");

        // 性能监控代码
        System.out.println("执行时长:" + (System.currentTimeMillis() - start)/1000f + "s");
    }
}

This part of the repeated code is generally collectively referred to as the cross-cutting logic code.

Insert picture description here

Problems with cross-cutting logic code:

Code duplication problem Cross-cutting logic code and business code are mixed together, the code is bloated, and the constant maintenance AOP is used to solve these problems

AOP takes another approach and proposes a horizontal extraction mechanism to separate the cross-cutting logic code and business logic code

Insert picture description here

Code splitting is relatively easy. The difficult part is how to silently apply horizontal logic code to the original business logic without changing the original business logic to achieve the same effect as the original one.

What problem does AOP solve? Through the above analysis, it can be found that AOP is
mainly used to solve: without changing the original business logic, enhance the cross-cutting logic code, fundamentally decouple it, and avoid the cross-cutting logic code duplication.

Why is AOP called aspect-oriented programming cut: refers to the cross-cutting logic, the original business logic code does not move, can only operate the cross-cutting logic code, so it is oriented to the cross-cutting logic

Surface: Cross-cutting logic codes often affect many methods. Each method is like a point, and multiple points form a surface. There is a concept of face here

Three ways to achieve aop:

Use native Spring API interface

It is to first create a service interface, then include the function of the target object, and then create an implementation class to implement this interface, and secondly, create a class to implement various enhanced interfaces, such as the pre-enhanced MethonBeforeAdvice
interface, and the post-enhanced AfterReturningAdvice interface, etc. , They are all enhancement methods to the target method, and finally configure aop:config in the xml configuration file, the entry point is the service implementation class

Custom aspect

In the custom aspect class, we can specify some custom aspect methods, before, after, around, etc. and
then configure the aop in applicationContext.xml. He needs to indicate which aspect class is, and then write the name in the method in the notification Enhancement method

Annotation method implementation

First, we create a class, write enhancement methods, before, after, etc., and then add annotations to the
class @Aspact to indicate that the current class is an aspect class, and then annotate the enhancement methods, such as @before @after, etc. The parameters inside are The path of the class to be enhanced, and finally enable annotation support in the configuration file

Bottom layer: jdk is used for interfaces, cglib is not used

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. Core InvocationHandler interface and Proxy class, InvocationHandler
invokes the code in the target class through the invoke() method reflection, dynamically weaving the cross-cutting 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, then 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.

3.spring affairs

The execution sequence of the transaction is as follows: 1. Open the transaction
2. Set the isolation level of the transaction (if not set, use the default isolation level)
3. Execute SQL
4. Submit the transaction

4. Problems that will arise from concurrent transactions
1. Dirty reads

The so-called dirty read means that transaction A reads data that has not yet been committed by transaction B. For example, when the bank withdraws money, transaction A starts the transaction, and then switches to transaction B, and transaction B starts the transaction -> withdraw 100 yuan, then switch back Transaction A, transaction A must read the original data in the database, because transaction B took 100 yuan and did not commit, the account balance in the database must still be the original balance, which is dirty reading.

2. Non-repeatable reading

The so-called non-repeatable read means that a certain data is read twice in a transaction, and the data read is inconsistent. Take the bank withdrawal as an example. Transaction A opens the transaction -> the bank card balance is found to be 1000 yuan, then switch to transaction B, transaction B opens the transaction -> transaction B takes away 100 yuan -> submit, the balance in the database becomes 900 yuan, switch back to transaction A at this time, transaction A checks again to find out that the account balance is 900 yuan, so for transaction A, the account balance data read twice in the same transaction is inconsistent, which is non-repeatable reading.

3. Phantom reading

The so-called phantom read refers to the discovery of unoperated data during an operation in a transaction. For example, for student information, transaction A opens transaction -> modify the sign-in status of all students on the day to false, then switch to transaction B, transaction B opens transaction -> transaction B inserts a piece of student data, then switches back to transaction A, and transaction A submits When I found a piece of data that I had not modified, this is a phantom reading, as if an illusion occurred. The premise for the appearance of phantom reading is that there are transactions that have inserted and deleted operations in concurrent transactions.

Spring transactions essentially use database transactions, and database transactions essentially use database locks, so spring transactions essentially use database locks. Opening spring transactions means using database locks;
spring transactions will only terminate or roll back when they catch exceptions. After try/catch in the program, handle exceptions by yourself without throwing, then the transaction will not be terminated or rolled back, losing the original role of the
transaction ; spring transaction will catch all exceptions, but only rollback database-related operations, and only The rollback will only be rolled back when the configuration such as rollbackForClassName="Exception" is declared; the
spring transaction will roll back all database operations in the same transaction, essentially rolling back the database operations on the same database connection;

Why spring transaction cannot guarantee data consistency and correctness of business logic:

1. If the transaction method throws an exception, the database operation will be rolled back at this time, but other methods that have been executed will not be rolled back, so the correctness of the business logic cannot be guaranteed;
2. Even if the transaction method does not throw an exception, data consistency cannot be guaranteed (Because the database operation in the transaction interface is submitted to the database after the execution of the entire interface logic is completed, it is likely to cause data consistency problems before and after the interface is finally submitted to the database), so that the correctness of the business logic cannot be guaranteed;

Isolation level The value of the isolation level causes problems
Read-Uncommitted 0 leads to dirty reads
Read-Committed 1 Avoid dirty reads, allow non-repeatable reads and phantom reads
Repeatable-Read 2 Avoid dirty reads, non-repeatable reads, allow phantom reads
Serializable 3 Serial In order to read, transactions can only be executed one by one, avoiding dirty reads, non-repeatable reads, and phantom reads. The execution efficiency is slow, so be cautious when using

Isolation level isolation level value The problem
Read-Uncommitted 0 Cause dirty reads
Read-Committed 1 Avoid dirty reads, allow non-repeatable reads and phantom reads
Repeatable-Read 2 Avoid dirty reads, non-repeatable reads, and allow phantom reads
Serializable 3 Serialized reads, transactions are executed one by one, avoiding dirty reads, non-repeatable reads, and phantom reads.

Isolation level in Spring

ISOLATION_READ_UNCOMMITTED
This is the lowest isolation level of the transaction, which allows another transaction to see the uncommitted data of this transaction. This isolation level will produce dirty reads, non-repeatable reads and phantom reads.
ISOLATION_READ_COMMITTED
guarantees that data modified by one transaction can only be read by another transaction after it is committed. Another transaction cannot read the data submitted by the transaction.
ISOLATION_REPEATABLE_READ //Repeatable read
This transaction isolation level can prevent dirty reads and non-repeatable reads. However, phantom reading may occur.
ISOLATION_SERIALIZABLE
This is the most expensive but most reliable transaction isolation level. Transactions are processed as sequential execution.

5.@Autowired annotation automatic assembly

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, then the bean will be assembled to the data specified by @Autowired;
if the query result is more than one, then @Autowired will search by name ;
If the result of the above search is empty, an exception will be thrown. When solving, use required=false.

6. What are the ways for sprin to automatically assemble beans

There are 5 kinds of automatic assembly in the Spring framework xml configuration:
no: The default method is not to perform automatic assembly, and the bean is assembled by manually setting the ref attribute.
byName: Automatic assembly is carried out by the name of the bean. If the property of one bean is the same as the name of another bean, automatic assembly will be carried out.
byType: Automatic assembly through the data type of the parameter.
constructor: Use the constructor to assemble, and the parameters of the constructor are assembled through byType.
autodetect: Automatic detection. If there is a construction method, it is automatically assembled by construct, otherwise it is automatically assembled by byType.

5. The concepts of several nouns in Spring AOP:

(1) Join point: refers to the method executed during the running of the program. In Spring AOP, a connection point always represents the execution of a method.
(2) Aspect: The extracted common module can be used to cross-cut multiple objects. Aspect can be regarded as a combination of Pointcut and
Advice. An aspect can be composed of multiple points and advices. In Spring AOP, aspects can be implemented using @AspectJ annotations on classes.
(3) Pointcut: The pointcut is used to define which Join points are to be intercepted.
The point of cut is divided into execution mode and annotation mode. The execution mode can use path expressions to specify which methods to intercept, such as specifying intercept add*, search*. The annotation method can specify which annotation-modified code is intercepted.
(4) Advice: Refers to
actions to be performed on the Join Point, that is, enhanced logic, such as permission checksums, log records, and so on. There are various types of notifications, including Around, Before, After, After
returning, and After throwing. (5) Target: The object that contains the connection point, also known as the object of the advice (Advice).
Since Spring AOP is implemented through dynamic proxy, this object is always a proxy object.
(6) Weaving: The process
of executing the enhanced logic (Advice) in the method of the target object (ie, the Join point) through the dynamic proxy .
(7) Introduction: Add additional methods or fields to the notified class. Spring allows the introduction of new interfaces (and corresponding implementations) to any object being proxied. For example, you can use an import to make the bean implement the
IsModified interface in order to simplify the caching mechanism.

6. What types of Spring advice (Advice) are there?

(1) Before Advice: The notification executed before the Join point. (2) After
Advice: The notification executed when the connection point exits (regardless of normal return or abnormal exit). (3) Around
Advice: A notification that surrounds a connection point. This is the most powerful type of notification.
Surround notifications can complete custom behaviors before and after the method is called. It can also choose whether to continue the execution of the connection point or directly return their own return value or throw an exception to end the execution.
(4) AfterReturning Advice: the notification executed after the connection point is completed normally (if the connection point throws an exception, it will not be executed)
(5) AfterThrowing advice: the method throws an exception Notification executed on exit

Insert picture description here

①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 getBean method is called for the first time.
②ApplicationContext, which creates all Beans at one time when the container is started. In this way, when the container starts, we can find configuration errors in Spring, which is conducive to checking whether the dependent properties are injected.
After the 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 are already created.

7. What is 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. Instantiation
  2. Attribute assignment Populate
  3. Initialization
  4. Destruction

(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 to instantiate it. For the ApplicationContext container, when the container is started, all beans are instantiated by obtaining the information in the BeanDefinition object.
(2) Setting 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 property 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 the Bean has implemented the BeanNameAware interface, it will call the setBeanName(String
beanId) implemented by it Method, here is the id value of the Bean in the Spring configuration file;
②If the Bean has implemented the BeanFactoryAware interface, the setBeanFactory() method implemented by it will be called, and the Spring factory itself will be passed.
③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 and init-method:
If the bean is configured with the init-method attribute in the Spring configuration file, the configured initialization method will be automatically invoked.
(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 the Bean initialization, it can be applied to memory or caching technology; the
above steps After completion, 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, the destroy() method it implements will be called;
(8) destroy-method:
Finally, if the Bean's Spring configuration When the destroy-method attribute is configured in, the configured destroy method will be automatically called.

8. Scope of bean in Spring:

(1) singleton: default scope, singleton bean, there is only one bean instance in each container.
(2) Prototype: Create an instance for each bean request.
(3) request: Create an instance for each request. After the request is completed, the bean will be invalidated and recycled by the garbage collector.
(4) Session: Similar to the request scope, the same session shares an instance, and different sessions use different instances.
(5) global-session: global scope, all sessions share an instance. If you want to declare a storage variable shared by all sessions, then the global variable needs to be stored in global-session.

9. 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;

10. 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 is found, the injection is assembled according to the type.

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

(1) Factory mode: BeanFactory is the embodiment of simple factory mode, 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 .

14. The difference between BeanFactory and factoryBean

BeanFactory is a Factory, that is, IOC container or object factory, and FactoryBean is a Bean. In Spring, all Beans are managed by the BeanFactory (that is, the IOC container). But for FactoryBean, this Bean is not a simple Bean, but a factory Bean that can produce or modify object generation. Its implementation is similar to the factory pattern and decorator pattern in the design pattern

Guess you like

Origin blog.csdn.net/zyf_fly66/article/details/114066855