1.后處理器
后處理器是對(duì)IOC容器功能的擴(kuò)展。按我的理解,擴(kuò)展的原理是在某動(dòng)作結(jié)束后再次調(diào)用指定的方法進(jìn)行擴(kuò)展處理。有點(diǎn)類似于AOP。
后處理器分兩種:Bean后處理器和容器后處理器。
1.1 Bean后處理器
Bean后處理器會(huì)在Bean實(shí)例化結(jié)束后(注意,該實(shí)例化應(yīng)該是指Bean類的實(shí)例化,還沒有進(jìn)行Spring中的注入等操作,并不是Spring最終返回的Bean),對(duì)其進(jìn)行近一步的增強(qiáng)處理,例如返回一個(gè)Bean的代理類。
Bean后處理器需要實(shí)現(xiàn)BeanPostProcessor
接口,該接口包含的postProcessBeforeInitialization
,postProcessAfterInitialization
分別在Bean初始化之前和之后回調(diào)。
如上圖,增強(qiáng)處理與
init-method
,InitializingBean
,destory-method
,DisposableBean
的執(zhí)行順序,增強(qiáng)處理永遠(yuǎn)在最外圍的。
下面給出Bean后處理器的Demo:
- 首先實(shí)現(xiàn)創(chuàng)建一個(gè)實(shí)現(xiàn)
BeanPostProcessor
的后處理器類
/**
* Bean后處理器Demo類,該處理類會(huì)對(duì)容器里面的所有Bean進(jìn)行后處理
* @author wangsz
*/
public class BeanPostProc implements BeanPostProcessor{
/**
* 在Bean初始化后,對(duì)容器中的bean進(jìn)行后處理,返回處理后的bean
*/
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("bean后處理器在["+beanName+"]初始化后對(duì)其進(jìn)行增強(qiáng)處理");
if(bean instanceof Person){
((Person) bean).setName("akq");
}
//該bean可以與舊bean截然不同,如返回一個(gè)該Bean的代理類
return bean;
}
/**
* 在Bean初始化前,對(duì)容器中的bean進(jìn)行后處理,返回處理后的bean
*/
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("bean后處理器在["+beanName+"]初始化前對(duì)其進(jìn)行增強(qiáng)處理");
//該bean可以與舊bean截然不同
return bean;
}
}
- 然后在Spring配置文件中加上這個(gè)Bean。這樣,該后處理類就會(huì)對(duì)容器里面的所有Bean進(jìn)行后處理。
<!--bean后處理器-->
<bean id="beanproc" class="test.wsz.spring.postprocessor.BeanPostProc" />
1.2 容器后處理器
Bean后處理器是對(duì)Bean實(shí)例化后進(jìn)行后處理的,而容器后處理器,顧名思義,就是對(duì)Spring容器進(jìn)行后處理,通常用于Spring容器實(shí)例化Bean之前,讀取配置文件元數(shù)據(jù),對(duì)其進(jìn)行修改。
容器后處理器需要實(shí)現(xiàn)BeanFactoryPostProcessor
接口,重寫該接口包含的postProcessBeanFactory
方法。
Spring中已提供了幾個(gè)常用的容器后處理器:
- PropertyPlaceholderConfigurer:屬性占位符配置器
- PropertyOverrideConfigurer:重寫占位符配置器
- CustomAutowireConfigurer:自定義自動(dòng)裝配的配置器
- CustomScopeConfigurer:自定義作用域的配置器
下面給出容器后處理器的Demo:
- 首先實(shí)現(xiàn)創(chuàng)建一個(gè)實(shí)現(xiàn)BeanFactoryPostProcessor的容器后處理器類
/**
* 容器后處理器Demo類,在容器實(shí)例化bean之前,讀取配置文件的元數(shù)據(jù),并修改
* @author wangsz
*/
public class BeanFactoryProc implements BeanFactoryPostProcessor{
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("Spring的容器是:"+beanFactory);
System.out.println("容器后處理器并沒有對(duì)BeanFactory的初始化做修改");
}
}
- 然后在Spring配置文件中加上這個(gè)Bean。
<!--容器后處理器-->
<bean id="beanfactoryproc" class="test.wsz.spring.postprocessor.BeanFactoryProc" />
2.AOP
Aspect Orient Pragramming:面向切面編程。
2.1 AOP的概念
這個(gè)術(shù)語不太好理解,下面我們用圖來一步步闡述它演變的過程。
現(xiàn)在有三個(gè)方法,我要在里面添加同一段代碼,比較low的方式,是將同一段代碼復(fù)制粘貼三遍:
改進(jìn)的方式是,我把這段代碼抽離到一個(gè)方法中,然后在三個(gè)方法中手動(dòng)調(diào)用這個(gè)抽離方法:
但是上面的方法仍然有些不方便。如果不是三個(gè)方法,是十個(gè),二十個(gè),那一個(gè)個(gè)的在里面寫方法的調(diào)用很麻煩。而且,如果增加需求,例如再次為方法一、二、三增加日志打印,再次為方法一、二、三增加參數(shù)檢驗(yàn),那么每次都得加個(gè)抽離方法,然后在方法一二三里面加調(diào)用。
AOP就是針對(duì)這些不便的進(jìn)一步優(yōu)化。我們將方法一二三看成一個(gè)切面,然后在這個(gè)切面上進(jìn)行增強(qiáng)處理。不需要方法一二三手動(dòng)調(diào)用抽離方法,抽離方法“自動(dòng)”進(jìn)行了調(diào)用:
通過上面的圖我們可以進(jìn)行一個(gè)總結(jié):AOP其實(shí)就是代理模式的一種體現(xiàn),將程序運(yùn)行過程看成一個(gè)切面,在切面上進(jìn)行公共的處理。
2.2 AOP的應(yīng)用
現(xiàn)在版本的Spring的AOP一般都是整合的AspectJ實(shí)現(xiàn)的。AspectJ框架是最早,功能比較強(qiáng)大的AOP實(shí)現(xiàn)之一,Spring中只是用到了它部分的功能,有興趣的朋友可以百度了解一下。
值得注意的是,AspectJ和Spring的實(shí)現(xiàn)方式的不同,AspectJ是編譯時(shí)對(duì)目標(biāo)類進(jìn)行增強(qiáng)(反編譯目標(biāo)類可發(fā)現(xiàn)多了內(nèi)容),而Spring是生成一個(gè)代理類進(jìn)行增強(qiáng)。
下面我們開始在Spring中配置AOP
- 首先在Maven中增加AspectJ的支持jar包,注意版本要和jdk符合,我之前用的jar包過老,導(dǎo)致aop測(cè)試時(shí)莫名出現(xiàn)一系列找不到包的異常。
<!--aop支持jar包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
- 在Spring的配置文件中增加內(nèi)容:
<!--beans中增加如下三個(gè)配置-->
<beans xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!--aspect配置
如果proxy-target-class 屬性值被設(shè)置為true,那么基于類的代理將起作用(這時(shí)需要cglib庫(kù))。
如果proxy-target-class屬值被設(shè)置為false或者這個(gè)屬性被省略,那么標(biāo)準(zhǔn)的JDK 基于接口的代理將起作用-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--Aspect Demo類-->
<bean class="test.wsz.spring.aop.AspectDemo" />
</beans>
如果不采用Spring的XML Schema的方法,也可以去除<beans ……>
對(duì)應(yīng)配置,增加:
<!--啟動(dòng)AspectJ支持-->
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
- 然后我們創(chuàng)建一個(gè)Aspect的測(cè)試Demo類:
@Aspect //聲明該類為切面類,在spring配置中加入該類的bean,ApplicationContext會(huì)自動(dòng)加載,將該Bean作為切面處理
public class AspectDemo {
/**
* 在方法執(zhí)行前進(jìn)行調(diào)用,value指定切入點(diǎn)
*/
@Before(value = "execution(* test.wsz.spring.bean..StoneAxe.useAxe(..))")
public void beforeTest() {
System.out.println("-----before stoneAxe.useAxe()-----");
}
/**
* 在方法正常執(zhí)行完成后進(jìn)行調(diào)用,value指定切入點(diǎn),也可用pointcut。returning指定返回形參
*/
@AfterReturning(returning = "returnValue", pointcut = "execution(* test.wsz.spring.bean..StoneAxe.useAxeTest(..))")
public void afterReturnTest(Object returnValue) {
System.out.println("-----after stoneAxe.useAxe()-----");
System.out.println("返回值是:" + returnValue);
}
/**
* 無論方法是否正常結(jié)束,只要完成后調(diào)用該方法
*/
@After(value = "execution(* test.wsz.spring.bean..StoneAxe.useAxeTest(..))")
public void afterTest() {
System.out.println("方法執(zhí)行完成,無論是正常完成還是異常終止執(zhí)行");
}
/**
* 在方法異常后調(diào)用,但并不能像catch一樣捕獲異常,異常仍然會(huì)拋給上級(jí)進(jìn)行處理
*
* @param e
* 方法中拋出的異常
*/
@AfterThrowing(throwing = "e", pointcut = "execution(* test.wsz.spring.bean..StoneAxe.useAxeTest(..))")
public void afterThrowingTest(Throwable e) {
System.out.println("方法拋出異常:" + e.getMessage());
}
/**
* 功能較強(qiáng)的增強(qiáng)方法,類似before和afterReturning的集合
* @param pjp 方法信息對(duì)象
* @return
* @throws Throwable
*/
@Around("execution(* test.wsz.spring.bean..StoneAxe.useAxeTest(..))")
public Object aroundTest(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("-----around-------");
System.out.println("方法執(zhí)行前");
Object object = pjp.proceed();
System.out.println("方法執(zhí)行后");
return object;
}
}
這個(gè)Demo類中演示了幾種切面的注解方法。xml的配置方法就不貼出來了,可自行百度。
為了方便,我們還可設(shè)定一個(gè)切點(diǎn),然后進(jìn)行引用:
// 定義一個(gè)切入點(diǎn),該切入點(diǎn)方法體中的代碼無效
@Pointcut("execution(* test.wsz.spring.bean..IronAxe.useAxe(..))") // 方法體中的代碼無效
public void mypointcut() {
System.out.println("-----pointcout-----");
}
/**
* 在方法執(zhí)行前進(jìn)行調(diào)用
*/
@Before(value = "mypointcut()")
public void before() {
System.out.println("-----before-----");
}
注意,幾種切面方法的執(zhí)行順序如下:
最后補(bǔ)充下切面execution
的規(guī)則
execution(<修飾符模式>?<返回類型模式><方法名模式>(<參數(shù)模式>)<異常模式>?)
舉一個(gè)例子說明: