Comprehensively understand the various knowledge points of the microservice architecture spring, covering all knowledge points

Foreword:

Recently, I have sorted out Spring-related knowledge points (required in interviews). During the process of sorting out, I found that my understanding of Spring was a little hazy, because we usually accept Spring’s single knowledge points or know but no code support. It's a bit hazy, so I took Spring knowledge points from the whole to the parts, and then to the last knowledge point. I think there are many friends or beginners who are a bit hazy about Spring like me, so I share them and write Incomplete and bad welcome to point out

what is spring

Spring is an open source framework. Spring is born to simplify enterprise-level development. Using spring, simple java beans can realize functions that only EJG can achieve before.

Spring is a lightweight Inversion of Control (IoC) and Aspect Oriented (AOP) container framework.

Features of spring

◆ Lightweight - Spring is lightweight in both size and overhead. The complete Spring framework can be distributed in a JAR file of just over 1MB in size. And the processing overhead required by Spring is also trivial. Furthermore, Spring is non-intrusive: typically, objects in a Spring application do not depend on Spring-specific classes.

◆ Inversion of Control - Spring promotes loose coupling through a technique called Inversion of Control (IoC). When IoC is applied, other objects that an object depends on are passed in passively, rather than the object creating or finding dependent objects by itself. You can think of IoC as the opposite of JNDI - instead of the object looking up dependencies from the container, the container proactively passes dependencies to it when the object is initialized without waiting for the object to request it.

◆ Aspect-oriented - Spring provides rich support for aspect-oriented programming, allowing cohesive development by separating the application's business logic from system-level services (such as auditing and transaction () management). Application objects do only what they are supposed to do - complete business logic - nothing more. They are not responsible for (or even aware of) other system-level concerns, such as logging or transaction support.

◆ Container - Spring contains and manages the configuration and life cycle of application objects, in the sense that it is a container where you can configure how each of your beans is created - based on a configurable prototype, your Beans can create a single instance or spawn a new one each time they are needed - and how they relate to each other. However, Spring should not be confused with traditional heavyweight EJB containers, which are often bulky and bulky and difficult to use.

◆ Framework - Spring can configure and combine simple components into complex applications. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides many basic functions (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.

What does Spring include

Core Technology IoC and AOP

Data access (persistence layer solution)

Web layer solution SpringMVC

Integrate (integrate with other open source frameworks)

 What are the benefits of using Spring

◆ Spring can effectively organize your middle-tier objects, whether you choose to use EJB or not. If you only use Struts or other frameworks that include J2EE-specific APIs, you'll find that Spring takes care of legacy issues.

◆ Spring can eliminate the excessive use of Singleton in many projects. In my experience, this is a major problem that reduces the testability and object-oriented nature of the system.

◆Spring can eliminate the need to use various formats of attribute customization files, and can be configured in a consistent way throughout the application and project. Ever wonder if a particular class has to read the Javadoc or even the source code to find a psychedelic property keyword or system property? With Spring, you can easily see the JavaBean properties of a class. The use of inversion controls (discussed below) helps accomplish this simplification.

◆ Spring can promote good programming habits through interfaces rather than classes, reducing programming costs to almost zero.

◆ Spring is designed to use it to create applications that rely on its APIs as little as possible. Most business objects in Spring applications do not depend on Spring.

◆ Applications built with Spring are easy to unit test.

◆Spring makes the use of EJB an implementation choice rather than an inevitable choice for application architecture. You can choose to use POJOs or local EJBs to implement the business interface without affecting the calling code.

◆ Spring helps you solve many problems without using EJB. Spring can provide an alternative to EJBs that are suitable for many web applications. For example, Spring can use AOP to provide declarative transactions without using an EJB container, and if you only need to deal with a single database, you don't even need a JTA implementation.

■ Spring provides a consistent framework for data access, whether using JDBC or O/R mapping products (such as Hibernate).

Spring really enables you to solve your problem with the simplest possible solution. These features are of great value.

To sum up, Spring has the following advantages:

◆Low intrusive design, extremely low code pollution

◆ Independent of various application servers, it can truly realize the promise of Write Once, Run Anywhere

◆Spring's DI mechanism reduces the complexity of business object replacement

◆Spring does not completely depend on Spring, and developers can freely choose part or all of the Spring framework

Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 521353348 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, microservice architecture principles, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot

What are the core classes in spring and what are the functions of each

BeanFactory: Generate a new instance, which can implement the singleton pattern

BeanWrapper: Provides unified get and set methods

ApplicationContext: Provides the implementation of the framework, including all the functions of BeanFactory

What are the commonly used classes and interfaces in spring

A: ApplicationContextAware interface

When a class needs to obtain an instance of ApplicationContext, it can implement the ApplicationContextAware interface.

B: ApplicationEvent abstract class

When you need to create a custom event, you can create a new class that inherits from the ApplicationEvent abstract class.

C: ApplicationListener interface

When you need to listen to custom events, you can create a new class that implements the ApplicationListener interface and configure this class into the Spring container.

D: BeanNameAware interface

When a bean needs to obtain its own id/name in the container, it can implement the BeanNameAware interface.

E: InitializingBean interface

When you need to do some special processing after all the properties of the bean are successfully set, you can make the bean implement the InitializingBean interface.

The effect is equivalent to the use of the bean's init-method attribute or the use of the @PostContsuct annotation.

The execution order of the three methods: first annotate, then execute the method defined in the InitializingBean interface, and finally execute the method specified by the init-method attribute.

F: DisposableBean interface

When you need to do some special processing before the bean is destroyed, you can make the bean implement the DisposableBean interface.

The effect is equivalent to the use of the destroy-method attribute of the bean or the use of the @PreDestory annotation.

The execution order of the three methods: first annotate, then execute the method defined in the DisposableBean interface, and finally execute the method specified by the destroy-method attribute.

G: BeanPostProcessor interface

When the managed beans need to be preprocessed, a new class that implements the BeanPostProcessor interface can be created and configured into the Spring container.

H: BeanFactoryPostProcessor interface

When the Bean Factory needs to be preprocessed, a new class that implements the BeanFactoryPostProcessor interface can be created and configured into the Spring container.

The principle of spring transaction

Transaction management methods: programmatic and declarative, spring recommends the latter method

The advantages of declarative transaction management are very obvious: there is no need to pay attention to transaction logic in the code, let Spring declarative transaction management be responsible for transaction logic, declarative transaction management does not need to be coupled with specific transaction logic, and can easily switch between different transaction logics.

What is IOC, what is DI, and what is the difference between them

Dependency Injection DI is a programming pattern and architectural model, sometimes called Inversion of Control, although technically, DI is a special implementation of IOC. Dependency injection refers to the application of an object to another object to provide a special The ability, for example: to pass a database connection as a parameter to an object's structure method instead of creating a connection within that object itself. The basic idea of ​​Inversion of Control and Dependency Injection is to transform the dependencies of a class from inside the class to the outside to reduce dependencies

Using inversion of control, when an object is created, an external entity that controls all objects in the system passes to it the references to the objects it depends on. It can also be said that dependencies are injected into objects. So, Inversion of Control is the inversion of responsibility for how an object obtains references to objects it depends on.

Several ways of bean injection properties

What is aop and what is the role of aop

Aspect-Oriented Programming (AOP) provides another way to think about program structure, and in this way makes up for the deficiencies of Object-Oriented Programming (OOP). In addition to classes, AOP provides aspects. Aspects modularize concerns, such as transaction management across multiple types and objects

A key component of Spring is the AOP framework, which allows you to choose whether to use AOP to provide declarative enterprise services, especially to replace EJB declarative services. The most important service is declarative transaction management, which builds on Spring's abstract transaction management. Allows users to implement custom aspects and use AOP to improve the use of OOP. Spring AOP can be regarded as an enhancement to Spring

Explanation of several important terms and concepts in AOP

Aspect: A modularity of concerns that may cut across multiple objects. Transaction management is a good example of cross-cutting concerns in J2EE applications. In Spring AOP, aspects can be implemented using generic classes (schema-based style) or with @Aspect annotations in ordinary classes (@AspectJ style).

Joinpoint: A specific point in the execution of a program, such as when a method is called or when an exception is handled. In Spring AOP, a join point always represents the execution of a method. By declaring a
parameter of type org.aspectj.lang.JoinPoint, the body part of the Advice can obtain the join point information.

Advice: An action performed at a particular Joinpoint of an aspect. There are various types of notifications, including "around", "before", and "after". Types of notifications are discussed in a later section. Many AOP frameworks, including Spring, use interceptors as their advice model and maintain a joinpoint-centric chain of interceptors.

Pointcut: An assertion that matches a Joinpoint. Advice is associated with a pointcut expression and runs on join points that satisfy this pointcut (for example, when a method of a particular name is executed). How a pointcut expression matches a join point is at the heart of AOP: Spring uses the AspectJ pointcut syntax by default.

Introduction: (also known as an 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 proxied object. For example, you can use an import to make the bean implement the IsModified interface in order to simplify the caching mechanism.

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

AOP Proxy (AOP Proxy): An object created by the AOP framework to implement the aspect contract (including functions such as informing method execution). In Spring, AOP proxies can be JDK dynamic proxies or CGLIB proxies. Note: With the newly introduced schema-based style and @AspectJ annotation style aspect declarations in Spring 2.0, proxy creation is transparent to users of these styles.

Weaving: Connect aspects to other application types or objects and create an advised object. These can be done at compile time (e.g. with the AspectJ compiler), class loading time and runtime. Spring, like other pure Java AOP frameworks, does weaving at runtime.

Type of notification:

Before advice: An advice that executes before a join point, but which cannot prevent execution before the join point (unless it throws an exception).

After returning advice: Advice that is executed after a join point completes normally: for example, a method returns normally without throwing any exceptions.

After throwing advice: Advice that executes when a method exits with an exception thrown.

After (finally) advice: Advice that is executed when a join point exits (whether it is a normal return or an abnormal exit).

Around Advice: Advice that surrounds a join point, such as a method call. This is the most powerful type of notification. Surround advice can be used to accomplish custom behavior before and after method calls. It also chooses whether to continue execution of the join point or simply return their own return value or throw an exception to end execution.

Wraparound notifications are the most commonly used type of notification. Most interception-based AOP frameworks, such as Nanning and JBoss4, only provide wraparound advice.

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

Please introduce the life cycle and scope of beans in the Spring framework

(1) bean definition

Used to define in the configuration file.

(2) bean initialization

There are two ways to initialize:

A. It is done by specifying the init-method attribute in the configuration file

B. Implement the
org.springframwork.beans.factory.InitializingBean interface

(3) bean call

There are three ways to get a bean instance and call it

(4) bean destruction

There are two ways to destroy

A. Use the destroy-method property specified in the configuration file

B. Implement the
org.springframwork.bean.factory.DisposeableBean interface

##Scope

singleton

When a bean is scoped to singleton, there will only be one shared bean instance in the Spring IoC container, and all requests to the bean will only return the same instance of the bean as long as the id matches the bean definition.

prototype

A prototype-scoped bean causes a new bean instance to be created each time the bean is requested (either by injecting it into another bean, or by calling the container's getBean() method programmatically). As a rule of thumb, you should use prototype scope for all stateful beans and singleton scope for stateless beans

request

In an HTTP request, a bean definition corresponds to an instance; that is, each HTTP request will have its own bean instance, which is created according to a bean definition. This scope is only valid in the context of a web-based Spring ApplicationContext.

session

In an HTTP Session, a bean definition corresponds to an instance. This scope is only available in web-based Spring

Valid in the case of ApplicationContext.

global session

In a global HTTP Session, a bean definition corresponds to an instance. Typically, only when using portlets

Valid when the context is used. This scope is only valid in the context of a web-based Spring ApplicationContext.

What are the initialization methods of beans

There are two ways to initialize beans.

1. Complete by specifying the init-method attribute in the configuration document

Implement a method for initializing Bean properties in the Bean class, such as init(), such as:

public class HelloWorld{
public String msg=null;
public Date date=null;
public void init() {
msg=”HelloWorld”;
date=new Date();
}
……
}

Then, set the init-mothod property in the configuration file:

2. Implement the 
org.springframwork.beans.factory.InitializingBean interface

Bean implements the InitializingBean interface and adds the afterPropertiesSet() method:

public class HelloWorld implement InitializingBean {
public String msg=null;
public Date date=null;
public void afterPropertiesSet() {
msg=”向全世界问好!”;
date=new Date();
}
……
}

Then, when all the properties of the bean are set by Spring's BeanFactory, the afterPropertiesSet() method will be automatically called to initialize the bean, so the configuration file does not need to specify the init-method attribute.

What are the calling methods of beans

There are three ways to get a bean and call it:

1. Use BeanWrapper

HelloWorld hw=new HelloWorld();
BeanWrapper bw=new BeanWrapperImpl(hw);
bw.setPropertyvalue(”msg”,”HelloWorld”);
system.out.println(bw.getPropertyCalue(”msg”));

2. Use BeanFactory

InputStream is=new FileInputStream(”config.xml”);
XmlBeanFactory factory=new XmlBeanFactory(is);
HelloWorld hw=(HelloWorld) factory.getBean(”HelloWorld”);
system.out.println(hw.getMsg());

3, use ApplicationConttext

ApplicationContext actx=new FleSystemXmlApplicationContext(”config.xml”);
HelloWorld hw=(HelloWorld) actx.getBean(”HelloWorld”);
System.out.println(hw.getMsg());

What are the ways to destroy beans

1. Use the destroy-method attribute in the configuration file

Similar to the initialization attribute init-methods, implement a method to revoke the bean in the bean class, and then specify it in the configuration file through the destruction-method, then when the bean is destroyed, Spring will automatically call the specified destruction method.

2. Implement the 
org.springframwork.bean.factory.DisposebleBean interface

If the DisposebleBean interface is implemented, Spring will automatically call the Destory method in the bean to destroy it, so the Destory method must be provided in the bean.

Introduce Spring's transaction management

A transaction is a unified commit or rollback operation for a series of database operations (such as inserting multiple pieces of data).

This prevents dirty data and prevents problems with database data.

In order to avoid this situation in development, transaction management is generally performed. Spring also has its own transaction management mechanism, which is generally managed by TransactionMananger, which can be accomplished through Spring injection.

Spring provides several classes for transaction processing:

TransactionDefinition //Transaction attribute definition

TranscationStatus //Represents the current transaction, which can be committed and rolled back.


PlatformTransactionManager is the basic interface provided by spring for managing transactions. There is an abstract class that implements AbstractPlatformTransactionManager. The transaction management classes we use, such as DataSourceTransactionManager, are all subclasses of this class.

General Transaction Definition Steps:

TransactionDefinition td = new TransactionDefinition(); 
TransactionStatus ts = transactionManager.getTransaction(td); 
try 
{ //do sth 
transactionManager.commit(ts); 
} 
catch(Exception e){transactionManager.rollback(ts);} 

The transaction management provided by spring can be divided into two categories: programmatic and declarative. Programmatic is more flexible, but the amount of code is large, and there are more repeated codes; declarative is more flexible than programmatic.

Programmatically mainly use transactionTemplate. Some commits, rollbacks, and a series of transaction object definitions are omitted, and transaction management objects need to be injected.

void add(){ 
transactionTemplate.execute( new TransactionCallback(){ 
pulic Object doInTransaction(TransactionStatus ts) 
{ //do sth} 
} 
} 
声明式: 
使用TransactionProxyFactoryBean: 
PROPAGATION_REQUIRED PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly 
围绕Poxy的动态代理 能够自动的提交和回滚事务 

org.springframework.transaction.interceptor.TransactionProxyFactoryBean

PROPAGATION_REQUIRED – supports the current transaction, if there is no current transaction, create a new transaction. This is the most common choice.

PROPAGATION_SUPPORTS – Support current transaction, if there is no current transaction, execute in non-transactional mode.

PROPAGATION_MANDATORY – supports the current transaction, throws an exception if there is no current transaction.

PROPAGATION_REQUIRES_NEW – create a new transaction, if there is a current transaction, suspend the current transaction.

PROPAGATION_NOT_SUPPORTED - Performs the operation in a non-transactional manner, suspending the current transaction if there is one.

PROPAGATION_NEVER – Execute non-transactionally, throw an exception if there is currently a transaction.

PROPAGATION_NESTED – If a transaction currently exists, execute within a nested transaction. If there are no current transactions, do something similar to PROPAGATION_REQUIRED.

Why have transaction propagation behavior

How to configure database driver in Spring

Use the "
org.springframework.jdbc.datasource.DriverManagerDataSource" data source to configure the database driver. An example is as follows:

Can the applicationContext.xml file in Spring be changed to another file name?

ContextLoaderListener is a ServletContextListener that is initialized when your web application starts. By default, it looks for
Spring's configuration in the WEB-INF/applicationContext.xml file. You can change the location of the Spring configuration file by defining an element named "contextConfigLocation". An example is as follows:

How to configure spring in web application

Add the following content to web.xml, and load
the content in /WEB-INF/applicationContext.xml when the web server is started.

Get the ApplicationContext instance through the following class

WebApplicationContextUtils.getWebApplicationContext

How to define hibernate mapping in Spring

Add the hibernate mapping file to the applicationContext.xml file in the web/WEB-INF directory. An example is as follows:

What are the roles of BeanFactory and ApplicationContext in spring

1. BeanFactory is responsible for reading bean configuration documents, managing bean loading, instantiation, maintaining dependencies between beans, and responsible for the declaration cycle of beans.

2. In addition to the functions provided by the above BeanFactory, ApplicationContext also provides more complete framework functions:

a. Internationalization Support

b. Resource access: Resource rs = ctx. getResource(”
classpath:config.properties”), “file:c:/config.properties”

c. Event delivery: by implementing the ApplicationContextAware interface

3. Commonly used methods to obtain ApplicationContext:


FileSystemXmlApplicationContext: Created from the file system or the xml configuration file specified by the url, the parameter is the configuration file name or an array of file names


ClassPathXmlApplicationContext: Created from the xml configuration file of the classpath, the configuration file can be read from the jar package


WebApplicationContextUtils: Read the configuration file from the root directory of the web application, you need to configure it in web.xml first, you can configure the listener or servlet to achieve

The default configuration file for these two methods is
web-inf/applicationContext.xml, and context-param can also be used to specify the configuration file

Difference between BeanFactory interface and ApplicationContext interface

* The ApplicationContext interface inherits the BeanFactory interface. The Spring core factory is the BeanFactory. The BeanFactory adopts lazy loading. The Bean will be initialized when the first getBean is obtained. The ApplicationContext will initialize the Bean when the configuration file is loaded.

* ApplicationContext is an extension to BeanFactory

internationalization

event delivery

Bean autowiring

Context implementation of various application layers

ApplicationContext is basically used in development, web projects use WebApplicationContext, and BeanFactory is rarely used

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
IHelloService helloService = (IHelloService) beanFactory.getBean("helloService");
helloService.sayHello();

How to configure applicationContext.xml file in web environment

How to implement internationalization in spring

Load a bean in applicationContext.xml

? Create multiple properties files in the src directory

? For non-English language, use native2ascii -encoding gb2312 source to convert the relevant content of the file

? Its naming format is message_language_country.

? The prompt information is displayed in the page, and the key name is the key value.

? When a country is given, the system will automatically load the properties information of the corresponding country.

?
Retrieve relevant information through applicationContext.getMessage("key name", "parameter", "area").

How Spring handles thread concurrency issues

Spring uses ThreadLocal to solve thread safety problems

We know that in general, only stateless beans can be shared in a multi-threaded environment. In Spring, most beans can be declared as singleton scope. It is because Spring
uses ThreadLocal to process non-thread-safe states in some beans (such as RequestContextHolder, TransactionSynchronizationManager, LocaleContextHolder, etc.), making them thread-safe, because stateful beans can be shared among multiple threads.

Both ThreadLocal and thread synchronization mechanisms are designed to solve the access conflict problem of the same variable in multiple threads.

In the synchronization mechanism, the lock mechanism of the object ensures that only one thread accesses the variable at the same time. At this time, the variable is shared by multiple threads. Using the synchronization mechanism requires the program to carefully analyze when to read and write the variable, when to lock an object, and when to release the object lock and other complicated issues. Program design and writing relatively difficult.

ThreadLocal solves the concurrent access of multiple threads from another perspective. ThreadLocal will provide each thread with an independent copy of the variable, thereby isolating the access conflict of multiple threads to the data. Since 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 into ThreadLocal.

Since any type of object can be held in ThreadLocal, the get() provided by the lower version of JDK returns an Object object, which requires type conversion. But JDK5.0 solves this problem well through generics, which simplifies the use of ThreadLocal to a certain extent.

To sum up, for the problem of multi-threaded resource sharing, the synchronization mechanism adopts the method of "exchanging time for space", while ThreadLocal adopts the method of "exchanging space for time". The former only provides a variable for different threads to queue for access, while the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

Briefly describe the difference between BeanFactory and ApplicationContext in Spring

Use BeanFactory to load beans from xml configuration file:

In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more functionality to it, some of which are perhaps closer to J2EE and centered around enterprise-level applications. In general, ApplicationContext is a complete superset of BeanFactory, and any description of BeanFactory functionality and behavior is also considered applicable to ApplicationContext

Compared with BeanFactory, ApplicationContext provides the following extension functions.

(a) Internationalization Support

(b) Resource Access

(c) Event propagation

(d) Multiple instance loading

Private message 666 for more videos, source code, notes

Guess you like

Origin blog.csdn.net/m0_67645544/article/details/124405258