preface

Spring is the most popular Java development technology, and its internal source code design is excellent.

The term Spring is familiar to Java developers. You probably use Spring every day and enjoy the services provided by the Spring ecosystem. Many Internet companies are now evaluating Spring as one of the most important aspects of a job interview.

It is no exaggeration to say that Spring is a must for Java programmers who want to make it to the top.

There are benefits at the end of the article

IT is difficult to be a programmer, but IT is even harder to be a programmer in 2020. With the increasing number of IT personnel, our competitive pressure is also increasing. In order to stand out from the crowd, the test is actually the breadth and depth of our technology stack.

What are the three general Spring interview philosophies? Why is that? How does it work?

! [](https://pic1.zhimg.com/v2-be76771c70ca3852041a25f256892244_b.jpeg)

What does Spring look like underneath? The following is a summary of the core knowledge of Spring, to share with you, I hope it can help you master Spring.

First share a Spring knowledge mind map to everyone

I. An overall introduction to Spring Framework functions

**Sring Core Container**

What modules do: Core and Beans modules are the foundation of the framework and provide IoC (reverse control) and dependency injection features. The basic concept here is BeanFactory, which provides a classic implementation of the Factory pattern to eliminate the need for programmatic singleton patterns and really allow you to separate dependencies and configurations from program logic

1. Core

This package contains the basic Core utility classes of the Spring framework, which are used by other Spring components. The Core module is the basic Core of other components.

2. Beans

It includes access to configuration files, create and manage bean and Inversion of Control | the Dependency

All classes related to the Injection (IoC/DI) operation

3.Context

The BeanFactory, or ApplicationContext.

Modules build on Core and Beans modules and provide a framework like JNDI register-like method of accessing objects. The Context module inherits Beans features and provides a number of extensions to the Spring core, adding support for internationalization (such as resource binding), event propagation, resource loading, and transparent creation of the Context. The Context module also supports some J2EE features. The ApplicationContext interface is the key to the Context module.

Essential difference :(beans that use BeanFacotry are loaded lazily,ApplicationContext is loaded non-lazily)

4.Expression Language

Modules provide a powerful expression language for querying and manipulating objects at run time. It is an extension of the Unifed Expression Language defined in the JSP 2.1 specification. The language supports setting/getting property values, assigning properties, calling methods, accessing accessiong the Context of Arrays, containers and indexers, logical and arithmetic operators, named variables, and retrieving objects by name from Spring’s IoC container. It also supports list projection, selection, and general list aggregation.

2. Use of the underlying annotations of the Spring IOC container

XML configuration file versus configuration class

1. Define Bean information based on XML form

<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <! Class =" com.demo.component.car "></ Bean ></ beans>Copy the code
Go to the container and read the Bean

public static void main( String[] args ) 
{ 
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); 
System.out.println(ctx.getBean("person")); 
} 
Copy the code

2. Define Bean information based on reading configuration classes

@Configuration public class MainConfig { @Bean public Person person(){ return new Person(); }}Copy the code
Read Bean information from container (passing in configuration class)

public static void main( String[] args ) 
{ 
AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(MainConfig.class); 
System.out.println(ctx.getBean("person")); 
} 
Copy the code

Spring Ioc container source code analysis

The core process for IOC container startup

i0:>org.springframework.context.support.AbstractApplicationContext#refresh

IOC container refresh process

i1>org.springframework.context.support.AbstractApplicationContext#prepareRefresh

Ready to refresh the container context prepareRefresh();

i2> ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

Initialize the container

i3>org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory

Register the system default components with the IOC container

i4>org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory

Subclass overrides do extra processing

i5>org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcess

Invokes the bean project’s back processor

i6>org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors

The backend handler of the registered bean

i7>org.springframework.context.support.AbstractApplicationContext#initMessageSource

Initialize internationalization resources

i8>org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster

Register event multicast

i9>org.springframework.context.support.AbstractApplicationContext#onRefresh

Left to the subclass implementation, SpringBoot is launched from here

i10>org.springframework.context.support.AbstractApplicationContext#registerListeners

Registers the event listener with the multicast

i11>org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization

Creating a bean instance

i12:org.springframework.context.support.AbstractApplicationContext#finishRefresh

The container is refreshed and eureka is launched from here

How does Spring solve loop dependencies

** What are circular dependencies? **

Cyclic dependence is A dependent on B, B dependent on A, or A dependent on B, B dependent on C,C dependent on A

! [](https://pic2.zhimg.com/v2-d2113a52b4c9792eb31e8c0b5ae29495_b.jpeg)

1. Code example:

//getter/setter
public class InstanceA {
 private InstanceB instanceB;
}
public class InstanceB {
private InstanceA instanceA;
}

<bean id="instanceA" class="com.tuling.circulardependencies.InstanceA">
<property name="instanceB" ref="intanceB"></property>
</bean>
<bean id="intanceB" class="com.tuling.circulardependencies.InstanceB">
<property name="instanceA" ref="instanceA"></property>
</bean>
Copy the code

2. Possible problems:

When creating beans, the IOC container instantiates instanceA first, in that order. And then suddenly I realized that my instanceA was dependent on my instanceB;

The IOC container then instantiates intanceB and finds instanceA dependencies when intanceB is instantiated. If the container does not, then IOC will execute the above process indefinitely until the memory exception program crashes.

3. Solutions:

Of course, Spring won’t let that happen. When the container discovers that beanB depends on beanA, it takes an early reference of the beanA object and injects this early reference into beanB so that beanB completes the instantiation first. BeanB completes the instantiation, beanA can get a reference to beanB, and beanA completes the instantiation. If you don’t know what “early quote” means, don’t worry…

Five, Spring Aop source code analysis

AOP core Concepts

1. Crosscutting concerns (which methods to cut into)

Which methods are intercepted, and how are they handled? These concerns are called crosscutting concerns

2. Aspect (extracting the non-business code originally mixed in the business logic code and putting the same functions into a class to form a aspect)

A class is an abstraction of object features, and a section is an abstraction of crosscutting concerns

3. Joinpoint (need to cut into the point)

The intercepted point. Since Spring only supports method type join points, join points in Spring refer to the method being intercepted. In fact, join points can also be fields or constructors

4. Pointcut

Definition of interception of join points

5. Advice

Notification refers to the code to be executed after intercepting the join point, and notification is divided into five categories: pre-notification, post-notification, abnormal, final, and circular notification

6. Target people

The target object of the proxy

7. Weave

The process of applying a facet to a target object and resulting in the creation of a proxy object

8. Introduction

Imports can dynamically add methods or fields to a class at run time without modifying the code

A simple case

Public interface Calculate {/** * add * @param numB * @param numB * @return */ int add(int numA,int numB); /** * numA * @numam numB * @return */ int numA,int numB; /** * @numa * @numb * @return */ int numA (int numA,int numB); /** ** @numa * @numam numB * @return */ int numA,int numB; }Copy the code

= = = = = = = = = = implementation class

public class TulingCalculate implements Calculate { 	public int add(int numA, int numB) { 		return numA+numB;	} 	public int reduce(int numA, int numB) {		return numA-numB;	} 	public int div(int numA, int numB) {		return numA/numB;	} 	public int multi(int numA, int numB) {		return numA*numB;	}}
Copy the code

= = = = = = = = = cut class

@Aspectpublic class TulingLogAspect { @Pointcut("execution(* com.tuling.TulingCalculate.*(..) )") public void pointCut(){}; @Before(value = "pointCut()") public void methodBefore(JoinPoint joinPoint){ String methodName = joinPoint.getSignature().getName(); System.out.println(" Array.asList (joinPoint.getargs ())) "); } @After(value = "pointCut()") public void methodAfter(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); System.out.println(" Array.asList (joinPoint.getargs ())); } @AfterReturning(value = "pointCut()") public void methodReturning(JoinPoint joinPoint ) { String methodName = joinPoint.getSignature().getName(); Println (" Array.asList (joinPoint.getargs ())) + array.asList (joinPoint.getargs ())); } @AfterThrowing(value = "pointCut()") public void methodAfterThrowing(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Println (" Array.asList (joinPoint.getargs ())) + array.asList (joinPoint.getargs ())); }}Copy the code

= = = = = = = = = = configuration class

@Configuration@EnableAspectJAutoProxy public class MainConfig { 	@Bean	public Calculate calculate() {		return new TulingCalculate();	} 	@Bean	public TulingLogAspect tulingLogAspect() {		return new TulingLogAspect();	}}
Copy the code

Spring transaction source code analysis

Transaction concept analysis

1. What are things?

A transaction is a logical set of units of execution that either all or none of them execute.

2. ACID

! [](https://pic3.zhimg.com/v2-eaaf82016fd16befa234ac61de93528e_b.jpeg)

What is ACID?

ACID refers to the four characteristics of transactions in a database management system DBMS

Eg: In a database system, a transaction consists of a complete logical process consisting of a series of database operations, such as a bank transfer, the amount deducted from the original account, and the amount added to the target account

! [](https://pic2.zhimg.com/v2-eac68398ddb1b9876da4913641a2db1d_b.png)

(1) Atomicity

Atomicity means that the operations can’t be split, so either the two operations are done at the same time, or they’re not done at all, and if the transaction goes wrong, then the transaction rolls back as if nothing happened, right

(2)Consistency

Consistency is also easier to understand, meaning that the database is always in a consistent state, one consistent state before a transaction starts, another consistent state after a transaction ends, and the transaction moves the database from one consistent state to another consistent state

(3)Isolation

The so-called independence means that the concurrent transactions do not affect each other. If the data to be accessed by one transaction is being modified by another transaction, the data accessed by the other transaction is not affected by the uncommitted transaction as long as the other transaction has not committed. In other words, the impact of one transaction is not visible to other transactions until the transaction commits

(4)Durability

If a transaction is committed, it is stored in the database forever

I don’t have enough space to cover everything else here, but the Spring core comes in a 176-page PDF document

Get this summary of Spring core knowledge

The last

Welcome everyone to exchange, like the article remember to pay attention to me a thumb-up, thank you for your support!