[ Original address ]: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 .

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

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就可以在多线程中共享了.












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








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




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


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

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























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

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

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

通知的类型将在后面部分进行讨论.许多AOP框架,包括Spring,都是以拦截器做通知模型, 并维护一个以连接点为中心的拦截器链.


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

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

这些可以在编译时(例如使用AspectJ编译器),类加载时和运行时完成. Spring和其他纯Java AOP框架一样,在运行时完成织入.

切入点(pointcut)和连接点(join point)匹配的概念是AOP的关键,这使得AOP不同于其它仅仅提供拦截功能的旧技术.


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

(2)返回后通知(After returning advice):在某连接点(join
(3)抛出异常后通知(After throwing advice):在方法抛出异常退出时执行的通知.
(4)后通知(After (finally) advice):当某连接点退出的时候执行的通知(不论是正常返回还是异常退出).
(5)环绕通知(Around Advice):包围一个连接点(join point)的通知,如方法调用.这是最强大的一种通知类型.