[ Original address ]:https://blog.csdn.net/a745233700/article/details/80959716
<https://blog.csdn.net/a745233700/article/details/80959716>
1,Spring What is it? ?

Spring It's a lightweight IoC and AOP Container frame . The purpose is to solve the complexity of enterprise application development , Use basic JavaBean To be completed by EJB Things done , It also provides more enterprise application functions ,Spring Is not limited to server-side development , From simplicity , In terms of testability and loose coupling , whatever Java All applications can be downloaded from Spring Benefit from .
2,Spring The advantages of ?

(1)spring It is a low invasion design , Code pollution is extremely low ;

(2)spring Of DI Mechanism reduces the complexity of business object replacement ;

(3) The container provides AOP technology , It is easy to implement such as permission interception , Monitoring and other functions during operation ;

(4) The coupling between components is reduced , The decoupling between software layers is realized ;

(5) Container provides singleton support ;

(6) You can use many of the services provided by the container , Such as transaction management , Message service, etc ;

(7) Container provides many auxiliary classes , It can accelerate the development of application ;

(8)spring It provides integration support for mainstream application frameworks , as hibernate,JPA,Struts etc.

(9) Independent of various application servers

(10)Spring A high degree of openness , Does not force applications to rely entirely on Spring, Developers are free to choose spring Part or all of .

3,Spring Of AOP understand :

AOP, It is generally called aspect oriented ( section ) programming , As a complement of object-oriented , It is used to dissect the inner part of the encapsulated object , Find out the public behaviors that affect multiple objects , And encapsulate it as a reusable module , This module is named “ section ”(Aspect), All aspects have nothing to do with business , But it is extracted and encapsulated by the logic called by business modules , Reduce duplicate code in the system , The coupling degree between modules is reduced , At the same time, the maintainability of the system is improved . It can be used for authority authentication , journal , transaction processing .
AOP The key to implementation is AOP Framework automatically created AOP agent ,AOP Agents are mainly divided into static agents and dynamic agents . The static proxy is represented by AspectJ; Dynamic proxy uses Spring
AOP On behalf of .


(1)AspectJ It is an enhancement of static proxy , So called static proxy , namely AOP The framework is generated during the compilation phase AOP proxy class , Therefore, it is also called compile time enhancement , He will AspectJ Weave into Java Bytecode , The runtime is enhanced AOP object .

(2)Spring
AOP Dynamic proxy used , The so-called dynamic proxy is AOP The framework does not modify bytecode , Instead, it generates a temporary method in memory each time it runs AOP object , this AOP Object contains all the methods of the target object , At the same time, the enhancement is done at the specific tangent point , And call back the method of the original object .

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

①JDK The dynamic proxy receives the proxy class through reflection , And the proxy class must implement an interface .JDK The core of dynamic proxy is InvocationHandler Interface and Proxy class . Method calls of generated proxy objects are delegated to the InvocationHandler.invoke() method , When we call the method of the proxy class object , this “ call ” Will be forwarded to invoke Method , Proxy class objects as proxy Parameter input , parameter method It identifies which method of the proxy class we are calling ,args Is the parameter of this method .
② If the target class does not implement the interface , that Spring AOP Will choose to use CGLIB To dynamically proxy the target class .CGLIB(Code Generation
Library), Is a code generated class library , A subclass object of the specified class can be generated dynamically at runtime , And override specific methods , You can add enhanced code when you override a method , So as to achieve AOP.CGLIB It is a dynamic proxy through inheritance , So if a class is marked as final, So it's not usable CGLIB Dynamic agent .


(3) The difference between static proxy and dynamic proxy lies in generation AOP The timing of the proxy object is different , relatively speaking AspectJ Static proxy has better performance , however AspectJ Specific compiler needs to be processed , and Spring
AOP No specific compiler processing is required .

4,Spring Of IoC understand :


(1)IOC It's inversion of control . That is, the creation right of the object is reversed Spring, Dependencies between programs are controlled by the container , The function is to realize the decoupling of the program , Not in the traditional implementation , Directly controlled by program code .( rely on ) Control is transferred from the application code itself to the external container , The container creates the instance according to the configuration file and manages the dependency relationship between each instance , Transfer of control , It's called reversal , The container dynamically injects some dependency into the component .BeanFactory
yes Spring IoC The concrete implementation and core interface of container , It provides an advanced configuration mechanism , Makes it possible to configure any type of object , Used to package and manage all kinds of bean.


(2) The most intuitive expression is ,IOC Let the creation of objects do not need to go new 了 , It can be done by spring Automatic production , It's used here java Reflection mechanism of , It is created dynamically at runtime through reflection , Call object .spring It is to create objects dynamically at runtime according to the configuration file , And call the method of the object .

(3)Spring Of IOC There are three injection methods :
The first is injection based on attributes , Also called set Method injection ;
The second is to inject according to the construction method ;
The third is injection based on annotations .

In detail :


(4)IoC, Inversion of control : Leaving objects to container management , You just need to spring Configuration file general configuration corresponding bean, And set related properties , Give Way spring The container generates instance objects and management objects of the class . stay spring When the container starts up ,spring You will be configured in the configuration file bean All initialized and assembled , And then when you need to call , Just the ones that have been initialized bean Assigned to you need to call these bean Class . Is to reverse the control of an object to spring Container management .

(5)DI mechanism (Dependency
Injection, Dependency injection ): It can be said that it is IoC One of the contents of , When the container instantiates the object, it will be called actively ( Or its dependent objects ) Injection to the calling object . Like objects A Need to operate database , We used to be in A Write your own code to get one Connection object , Yes
spring We just need to tell spring,A You need one of them Connection, As for this Connection How to construct it , When to construct ,A No need to know . When the system is running ,spring Will make one at the right time Connection, And then it's like an injection , Injection to A among , This completes the control of the relationship between the objects .

IoC Keep the components that work together loosely coupled , and AOP Programming allows you to separate the functions that are distributed across the application layers to form reusable functional components .

5,BeanFactory and ApplicationContext What's the difference? ?

BeanFactory and ApplicationContext yes Spring The two core interfaces of , And among them ApplicationContext yes BeanFactory Sub interface of . They can all be used as Spring Container for , generate Bean Instance , And manage the Bean.


(1)BeanFactory: yes Spring The bottom interface in it , Provides the simplest container functionality , Responsible for reading bean Configuration document , Administration bean Loading and instantiation of , maintain bean The dependency relationship between , be responsible for bean Life cycle of , But it can't be supported spring Of aop Function and web application .


(2)ApplicationContext Interface as BeanFactory Derived from , So it has BeanFactory All functions . and ApplicationContext It also extended the function , Work in a more framework oriented way and layer context and implement inheritance , Compared with BeanFactorty,ApplicationContext The following functions are also provided :

① All are initialized by default Singleton, You can also cancel pre initialization through configuration .

② inherit MessageSource, Therefore, it supports internationalization .

③ Resource access , Like visiting URL And documents .

④ Event mechanism .

⑤ Load multiple configuration files at the same time .

⑥ Start and create in declarative mode Spring container .

⑦ Load multiple ( There is an inheritance relationship ) context , So that each context focuses on a specific level , For example, applied web layer .


(3)①BeanFactroy The injection is in the form of delayed loading Bean Of , That is, only after using a certain Bean Time ( call getBean()), That's right Bean Load instantiation , such , We can't find something that exists Spring Configuration of . If Bean One of the properties of is not injected ,BeanFacotry After loading , Until the first call is used getBean Method will throw an exception .

② and ApplicationContext On the contrary , It is when the container starts , Created all at once Bean. such , On container startup , We can find out Spring Configuration error in , This is helpful to check whether the dependent attributes are injected .
ApplicationContext All single instances are preloaded after startup Bean, By preloading a single instance bean , Make sure that when you need it , You don't have to wait , Because they're already created .
③ Relative to basic BeanFactory,ApplicationContext The only drawback is that it takes up memory space . When the application is configured Bean More , The program starts slowly .

(4)BeanFactory It is usually created programmatically ,ApplicationContext It can also be created declaratively , If used ContextLoader.


(5)BeanFactory and ApplicationContext Both support it BeanPostProcessor,BeanFactoryPostProcessor Use of , But the difference between the two is that :BeanFactory Manual registration required , and ApplicationContext It's automatic registration .

6, explain Spring Several kinds of support bean Scope of .

Spring In container bean It can be divided into 5 Range :

(1)singleton: such bean The scope is default , This scope ensures that no matter how many requests are received , There is only one in each container bean An example of , The pattern of the singleton is determined by bean
factory Self maintenance .
(2)prototype: The range of the original form is opposite to that of the single case , For each bean Request an instance .
(3)request: On request bean Within the scope, an instance is created for each network request from a client , After the request is completed ,bean Will fail and be recycled by the garbage collector .
(4)Session: Similar to request scope , Make sure that each session One of them bean An example of , stay session After expiration ,bean It's not going to work .

(5)global-session:global-session and Portlet Application related . When your application is deployed in Portlet When working in a container , It contains a lot portlet. If you want to state that all portlet If you share global storage variables , Then this global variable needs to be stored in the global-session in . Global scope and Servlet Medium session The scope effect is the same .

7, Please explain Spring Bean Life cycle of ?

Other addresses :https://www.cnblogs.com/zrtqsk/p/3735273.html
<https://www.cnblogs.com/zrtqsk/p/3735273.html>

First of all Servlet Life cycle of : instantiation , initial init, Receive request service, Destruction destroy;

Spring In context Bean The life cycle is similar , as follows :

(1) item base Bean-- That's what we often say new;

(2) according to Spring Context pair instantiated Bean Configure -- that is IOC injection ;


(3) If this Bean It's done BeanNameAware Interface , It will be called to implement setBeanName(String) method , Here's what we're passing Spring In the configuration file Bean Of id value ;


(4) If this Bean It's done BeanFactoryAware Interface , It will be called to implement setBeanFactory(setBeanFactory(BeanFactory) The message is Spring The factory itself ( You can get other things in this way Bean, You just need to Spring Configure a common Bean Can );


(5) If this Bean It's done ApplicationContextAware Interface , Will call setApplicationContext(ApplicationContext) method , afferent Spring context ( In the same way, steps can be implemented 4 Content of , But by 4 better , because ApplicationContext yes BeanFactory Sub interface of , There are more ways to do it );

(6) If this Bean Connected BeanPostProcessor Interface , Will be called postProcessBeforeInitialization(Object
obj, String
s) method ,BeanPostProcessor It is often used as a Bean Content changes , And because this is in the Bean Call that method at the end of initialization , It can also be used in memory or cache technology ;

(7) If Bean stay Spring Configuration file init-method Property automatically calls its configured initialization method .

(8) If this Bean Connected BeanPostProcessor Interface , Will be called postProcessAfterInitialization(Object
obj, String s) method ,;


notes : This can be applied after the above work is completed Bean了, So this one Bean It's a Singleton Of , So in general, we call the same id Of Bean Will be the same instance in the content address , Of course Spring You can also configure the Singleton.

(9) When Bean When no longer needed , It goes through the clean-up phase , If Bean Yes DisposableBean This interface , Will call its implementation destroy() method ;

(10) last , If this Bean Of Spring Configured in configuration destroy-method attribute , Its configured destroy method is called automatically .

In addition, we describe the application here Spring context Bean Life cycle of , If applied Spring That's the factory of BeanFactory Remove the first 5 Step by step Ok了.

8,Spring in bean Loading process of :

(1) Get profile resource ;

(2) For acquired xml The resources should be treated and inspected ;

(3) Handling packaging resources ;

(4) Analysis and processing of packaged resources ;

(5) Load extraction bean And register ( Add to beanDefinitionMap in ).

9,Spring Singleton in framework Beans Is it thread safe ?
Spring The framework does not have a single instance bean Any multi-threaded encapsulation processing . On singleton bean The problem of thread safety and concurrency needs to be solved by developers themselves . But in fact , Most of them Spring
bean There is no mutable state ( such as Serview Class and DAO class ), So in a way Spring Single example of bean It's thread safe . If your bean If there are multiple states ( such as
View Model object ), You need to ensure thread safety yourself .
The simplest solution is to change polymorphism bean The scope of is defined by “singleton” Change to “prototype”.

10,Spring How to deal with thread concurrency ?

Spring use ThreadLocal Solving thread safety issues .


We know that in general 况下,只有有状态的Bean才可以在多线程环境下共享,在Spring中,绝大部分Bean都可以声明为singleton作用域.就是因为Spring对一些Bean(如RequestContextHolder,TransactionSynchronizationManager,LocaleContextHolder等)中非线程安全状态采用ThreadLocal进行处理,让它们也成为线程安全的状态,因为有状态的Bean就可以在多线程中共享了.

ThreadLocal和线程同步机制都是为了解决多线程中相同变量的访问冲突问题.


(1)在同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量.这时该变量是多个线程共享的,使用同步机制要求程序慎密地分析什么时候对变量进行读写,什么时候需要锁定某个对象,什么时候释放对象锁等繁杂的问题,程序设计和编写难度相对较大.


(2)而ThreadLocal则从另一个角度来解决多线程的并发访问.ThreadLocal会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突.因为每一个线程都拥有自己的变量副本,从而也就没有必要对该变量进行同步了.ThreadLocal提供了线程安全的共享对象,在编写多线程代码时,可以把不安全的变量封装进ThreadLocal.


(3)概括起来说,对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式.前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响.

11,请解释Spring自动装配模式的区别?

在Spring框架中共有5种自动装配:

(1)no:这是Spring框架的默认设置,在该设置下自动装配是关闭的,开发者需要自行在bean定义中用标签明确的设置依赖关系.


(2)byName:该选项可以根据bean名称设置依赖关系.当向一个bean中自动装配一个属性时,容器将根据bean的名称自动在配置文件中查询一个匹配的bean.如果找到的话,就装配这个属性,如果没找到的话就报错.


(3)byType:该选项可以根据bean类型设置依赖关系.当向一个bean中自动装配一个属性时,容器将根据bean的类型自动在在配置文件中查询一个匹配的bean.如果找到的话,就装配这个属性,如果没找到的话就报错.


(4)constructor:构造器的自动装配和byType模式类似,但是仅仅适用于与有构造器相同参数的bean,如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常.


(5)autodetect:该模式自动探测使用构造器自动装配或者byType自动装配.首先,首先会尝试找合适的带参数的构造器,如果找到的话就是用构造器自动装配,如果在bean内部没有找到相应的构造器或者是无参构造器,容器就会自动选择byTpe的自动装配方式.

12,Spring 控制器的加载过程:(XML版)

(1)Web容器创建;

(2)上下文创建,但未初始化;

(3)监听器创建,并注册到Context上;

(4)上下文初始化;

(5)通知到监听者,Spring配置文件/@Configuration加载;

(6)Load-on-startup>0的ServletConfig创建,springMVC的DispatcherServlet此时创建.


PS:Spring容器时SpringMVC的父容器.Spring的AOP在Spring的上下文创建时就会创建;如果想要代理SpringMVC的控制层,需要将配置写到SpringMVC的配置文件下.

13,Spring 框架中都用到了哪些设计模式?

(1)代理模式—在AOP和remoting中被用的比较多.

(2)单例模式—在spring配置文件中定义的bean默认为单例模式.

(3)工厂模式—BeanFactory用来创建对象的实例.

(4)模板方法—用来解决代码重复的问题.比如. RestTemplate, JmsTemplate, JpaTemplate.

(5)前端控制器—Spring提供了DispatcherServlet来对请求进行分发.

(6)视图帮助(View Helper )—Spring提供了一系列的JSP标签,高效宏来辅助将分散的代码整合在视图里.

(7)依赖注入—贯穿于BeanFactory / ApplicationContext接口的核心理念.

14,Spring事务的种类和各自的区别:

spring支持编程式事务管理和声明式事务管理两种方式:


(1)编程式事务管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManager.对于编程式事务管理,spring推荐使用TransactionTemplate.


(2)声明式事务管理建立在AOP之上的.其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务.声明式事务最大的优点就是不需要通过编程的方式管理事务,这样就不需要在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明(或通过基于@Transactional注解的方式),便可以将事务规则应用到业务逻辑中.


(3)显然声明式事务管理要优于编程式事务管理,这正是spring倡导的非侵入式的开发方式.声明式事务管理使业务代码不受污染,一个普通的POJO对象,只要加上注解就可以获得完全的事务支持.和编程式事务相比,声明式事务唯一不足地方是,后者的最细粒度只能作用到方法级别,无法做到像编程式事务那样可以作用到代码块级别.

15,spring的事务传播行为:
spring事务的传播行为说的是当一个方法调用另一个方法时,事务该如何操作.
(1)PROPAGATION_REQUIRED:如果当前没有事务,就创建一个新事务,如果当前存在事务,就加入该事务,该设置是最常用的设置.

(2)PROPAGATION_SUPPORTS:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就以非事务执行.‘

(3)PROPAGATION_MANDATORY:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就抛出异常.

(4)PROPAGATION_REQUIRES_NEW:创建新事务,无论当前存不存在事务,都创建新事务.

(5)PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起.

(6)PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常.


(7)PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务内执行.如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作.

16,Spring事务的实现方式和实现原理:

(1)划分处理单元——IOC:


由于spring解决的问题是对单个数据库进行局部事务处理的,具体的实现首相用spring中的IOC划分了事务处理单元.并且将对事务的各种配置放到了ioc容器中(设置事务管理器,设置事务的传播特性及隔离机制).

(2)AOP拦截需要进行事务处理的类:


Spring事务处理模块是通过AOP功能来实现声明式事务处理的,具体操作(比如事务实行的配置和读取,事务对象的抽象),用TransactionProxyFactoryBean接口来使用AOP功能,生成proxy代理对象,通过TransactionInterceptor完成对代理方法的拦截,将事务处理的功能编织到拦截的方法中.


读取ioc容器事务配置属性,转化为spring事务处理需要的内部数据结构(TransactionAttributeSourceAdvisor),转化为TransactionAttribute表示的数据对象.

(3)对事物处理实现(事务的生成,提交,回滚,挂起):


spring委托给具体的事务处理器实现.实现了一个抽象和适配.适配的具体事务处理器:DataSource数据源支持,hibernate数据源事务处理支持,JDO数据源事务处理支持,JPA,JTA数据源事务处理支持.这些支持都是通过设计PlatformTransactionManager,AbstractPlatforTransaction一系列事务处理的支持.为常用数据源支持提供了一系列的TransactionManager.

(4)结合:


PlatformTransactionManager实现了TransactionInterception接口,让其与TransactionProxyFactoryBean结合起来,形成一个Spring声明式事务处理的设计体系.

17.解释一下Spring AOP里面的几个名词:

(1)切面(Aspect):一个关注点的模块化,这个关注点可能会横切多个对象.事务管理是J2EE应用中一个关于横切关注点的很好的例子. 在Spring
AOP中,切面可以使用通用类(基于模式的风格) 或者在普通类中以 @Aspect 注解(@AspectJ风格)来实现.

(2)连接点(Joinpoint):在程序执行过程中某个特定的点,比如某方法调用的时候或者处理异常的时候. 在Spring AOP中,一个连接点 总是
代表一个方法的执行. 通过声明一个org.aspectj.lang.JoinPoint类型的参数可以使通知(Advice)的主体部分获得连接点信息.


(3)通知(Advice):在切面的某个特定的连接点(Joinpoint)上执行的动作.通知有各种类型,其中包括“around”,“before”和“after”等通知.
通知的类型将在后面部分进行讨论.许多AOP框架,包括Spring,都是以拦截器做通知模型, 并维护一个以连接点为中心的拦截器链.


(4)切入点(Pointcut):匹配连接点(Joinpoint)的断言.通知和一个切入点表达式关联,并在满足这个切入点的连接点上运行(例如,当执行某个特定名称的方法时).
切入点表达式如何和连接点匹配是AOP的核心:Spring缺省使用AspectJ切入点语法.

(5)引入(Introduction):(也被称为内部类型声明(inter-type declaration)).声明额外的方法或者某个类型的字段.
Spring允许引入新的接口(以及一个对应的实现)到任何被代理的对象.例如,你可以使用一个引入来使bean实现 IsModified 接口,以便简化缓存机制.

(6)目标对象(Target Object): 被一个或者多个切面(aspect)所通知(advise)的对象.也有人把它叫做 被通知(advised)
对象. 既然Spring AOP是通过运行时代理实现的,这个对象永远是一个 被代理(proxied) 对象.

(7)织入(Weaving):把切面(aspect)连接到其它的应用程序类型或者对象上,并创建一个被通知(advised)的对象.
这些可以在编译时(例如使用AspectJ编译器),类加载时和运行时完成. Spring和其他纯Java AOP框架一样,在运行时完成织入.

切入点(pointcut)和连接点(join point)匹配的概念是AOP的关键,这使得AOP不同于其它仅仅提供拦截功能的旧技术.
切入点使得定位通知(advice)可独立于OO层次.
例如,一个提供声明式事务管理的around通知可以被应用到一组横跨多个对象中的方法上(例如服务层的所有业务操作).

18,通知有哪些类型?

(1)前置通知(Before advice):在某连接点(join point)之前执行的通知,但这个通知不能阻止连接点前的执行(除非它抛出一个异常).

(2)返回后通知(After returning advice):在某连接点(join
point)正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回.
(3)抛出异常后通知(After throwing advice):在方法抛出异常退出时执行的通知.
(4)后通知(After (finally) advice):当某连接点退出的时候执行的通知(不论是正常返回还是异常退出).
(5)环绕通知(Around Advice):包围一个连接点(join point)的通知,如方法调用.这是最强大的一种通知类型.
环绕通知可以在方法调用前后完成自定义的行为.它也会选择是否继续执行连接点或直接返回它们自己的返回值或抛出异常来结束执行.
环绕通知是最常用的一种通知类型.大部分基于拦截的AOP框架,例如Nanning和JBoss4,都只提供环绕通知.