Spring配置AOP實現定義切入點和織入加強

XML裏的id=」」記得全小寫html

通過AOP的配置後,能夠切入日誌功能、訪問切入、事務管理、性能監測等功能。java

首先實現這個織入加強須要的jar包,除了經常使用的node

com.springsource.org.apache.commons.logging-1.1.1.jar,spring

com.springsource.org.apache.log4j-1.2.15.jar,express

spring-beans-3.2.0.RELEASE.jar,apache

spring-context-3.2.0.RELEASE.jar,app

spring-core-3.2.0.RELEASE.jar,ide

spring-expression-3.2.0.RELEASE.jar以外還須要性能

spring-aop-3.2.0.RELEASE.jar,測試

com.springsource.org.aopalliance-1.0.0.jar,(aop聯合jar)

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar(織入方向jar)三個包。

而後我有一個接口

public interface Hello {

public void say();

}

和一個實現類

public class HelloImpl implements Hello{

public void say(){

System.out.println("執行say方法");

}

}

和兩個加強類

前置加強:

public class LogBefor implements MethodBeforeAdvice{

@Override

public void before(Method method, Object[] args, Object target)

throws Throwable {

System.out.println(method);

System.out.println(args);

System.out.println(target);

}

}

後置加強:

public class LogAfter implements AfterReturningAdvice{

@Override

public void afterReturning(Object returnValue, Method method,

Object[] args, Object target) throws Throwable {

System.out.println("返回值"+returnValue);

System.out.println("方法:"+method);

System.out.println("參數:"+args);

System.out.println("被代理對象:"+target);

}

}

接下來還須要在Spring配置文件中beans元素中須要添加aop的名稱空間,以導入與AOP相關的標籤:如:

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xmlns:aop="http://www.springframework.org/schema/aop"

     xsi:schemaLocation="http://www.springframework.org/schema/beans

         http://www.springframework.org/schema/beans/spring-beans.xsd

         http://www.springframework.org/schema/aop

         http://www.springframework.org/schema/aop/spring-aop.xsd">   

這裏比以前的多了:xmlns:aop="http://www.springframework.org/schema/aop"

在xsi:schemaLocation裏多了兩個

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd;

接下來在Spring配置文件中實現AOP配置,如個人xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xmlns:aop="http://www.springframework.org/schema/aop"

     xsi:schemaLocation="http://www.springframework.org/schema/beans

         http://www.springframework.org/schema/beans/spring-beans.xsd

         http://www.springframework.org/schema/aop

         http://www.springframework.org/schema/aop/spring-aop.xsd">

         

<bean id="hello" class="cn.cnti.aop.HelloImpl"></bean>

 

<!-- 加強類 -->

<bean id="before" class="cn.cnti.aop.LogBefor">

</bean>

<bean id="after" class="cn.cnti.aop.LogAfter">

</bean>

 

<aop:config>

<!-- 定義切入點 -->

         <aop:pointcut id="pointcut"

                    expression="execution(public void say())"/>

         <aop:advisor advice-ref="before" pointcut-ref="pointcut"/>

         <aop:advisor advice-ref="after" pointcut-ref="pointcut"/>

   </aop:config>

 </beans> 

若是記不清楚的話,spring-framework-3.2.0.RELEASE-distspring-framework-3.2.0.RELEASEdocsspring-framework-referencehtmlaop.html打開後搜索aop會有模板。

其中execution是切入點指示符,它的括號中是一個切入點表達式,能夠配置要切入的方法,切入點表達式支持模糊匹配:

Public * say(entity.User):」*」表示匹配全部類型的返回值

Public void *(entity.User):」*」表示匹配全部方法名。

Public void say(..):」..」表示匹配全部參數個數和類型。

* cn.jnti.service.*.*(..):這個表達式匹配cn.jnti.service包下全部類的全部方法。

* cn.jnti.service..*.*(..):這個表達式匹配cn.jnti.service包及其子包下全部類的全部方法。

等等,還有許多。

最後咱們測試一下:

@Test

public void mtest(){

BeanFactory bf=new  ClassPathXmlApplicationContext("appContext.xml");

Hello h = (Hello) bf.getBean("hello");

h.say();

}

 ***********************************************************************************************************

若是想實現日誌輸出的話,在這個原有jar包的基礎上須要

cglib-nodep-2.2.3.jarorg.springframework.asm-3.1.1.RELEASE.jar

而後再前置加強和後置加強裏各加一個靜態常量:

Private static final Logger log=Logger.getLogger(LogBefor.class);

Private static final Logger log=Logger.getLogger(LogAfter.class);

而後在方法裏直接用lo.info(「調用」+target6」的」+method.getName()+」方法」+」參數是:」+Arrays.toString(args));就好了。

*****************************************************************************************************************************************

環繞加強:

首先有一個一個User類裏面有name,price屬性。

有一個接口:

public interface UserService {

 Object save(User user);

}

有一個實現類:

public class UserServiceImpl implements UserService {

@Override

public Object save(User user) {

System.out.println(user.getName()+"存了"+user.getPrice()+"$");

return true;

}

}

個人循環加強類實現MethodInterceptor(是在importorg.aopalliance.intercept.MethodInterceptor包下):

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

 

public class Surround implements MethodInterceptor{

 

@Override

public Object invoke(MethodInvocation arg0) throws Throwable {

System.out.println("我進循環加強了!");

Object[] objects = arg0.getArguments();

for (Object obj : objects) {

System.out.println(obj);

}

User user=(User) objects[0];

if(user.getPrice()<0){

System.out.println("存款不能爲負數!");

return false;

}else{

//放行

return arg0.proceed();

}

}

}

個人xml配置:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans

         http://www.springframework.org/schema/beans/spring-beans.xsd

         http://www.springframework.org/schema/aop

         http://www.springframework.org/schema/aop/spring-aop.xsd">

 

<bean id="usersericeimpl" class="cn.cnti.aop.UserServiceImpl">

</bean>

<bean id="surround" class="cn.cnti.aop.Surround"></bean>

<!-- 加強類 -->

<aop:config>

<!-- 定義切入點 -->

<aop:pointcut id="pointcut" expression="execution(* cn.cnti.aop..*.*(..))" />

<aop:advisor advice-ref="surround" pointcut-ref="pointcut" />

</aop:config>

個人測試類:

@Test

public void testAround(){

BeanFactory bf=new ClassPathXmlApplicationContext("appContext.xml");

UserService us= (UserService) bf.getBean("usersericeimpl");

Object object = us.save(new User("sp",101));

System.out.println(object);

}

 ***********************************************************************************************************

異常拋出加強:

只須要有一個類實現ThrowsAdvice接口:

import java.lang.reflect.Method;

import org.springframework.aop.ThrowsAdvice;

public class ErrorLogger implements ThrowsAdvice{

public void afterThrowing(Method method,Object[] args,Object target,Exception e){

System.out.println("調用"+target+"的"+method.getName()+"方法時,發生異常"+e);

}

}

,可是

經過ThrowsAdvice接口實現異常拋出加強。ThrowsAdvice接口中並無定義任何方法。

可是咱們在定義異常拋出的加強方法時必須遵照如下方法簽名。

afterThrowing(Method method,Object[] args,Object target,Exception e)

這裏規定了方法名必須是afterThrowing。方法的入參只有最後一個是必須的,前三個入參是可選的,

可是前3個參數要麼都提供,要麼一個也不提供。

而後在xml配置裏再加上:

<!-- 異常拋出加強 -->

<bean id="errorlogger" class="cn.cnti.aop.ErrorLogger"></bean>

<aop:config>

<!-- 定義切入點 -->

<aop:pointcut id="pointcut" expression="execution(* cn.cnti.aop..*.*(..))" />

<aop:advisor advice-ref="errorlogger" pointcut-ref="pointcut" />

</aop:config>

由於沒有異常的話是不會看到效果的,因此要手動製造一個異常:

public Object save(User user) {

System.out.println(user.getName()+"存了"+user.getPrice()+"$");

int a=1/0;

return true;

}

******************************************************************************************************

使用註解標註加強:

個人註解加強類:

package cn.cnti.annotation;

 

import org.aspectj.lang.annotation.AfterReturning;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

//@Aspect註解將UserBizAdvice定義爲切面

@Aspect

public class UserBizAdvice{

//前置加強

@Before("execution(* cn.cnti.annotation..*.*(..))")

public void before(){

System.out.println("即將調用業務方法!");

}

//後置加強

@AfterReturning("execution(* cn.cnti.annotation..*.*(..))")

public void afterReturning(){

System.out.println("後置加強");

}

}

配置文件除了要導入aop命名空間外,只須要在配置文件中添加

<aop:aspectj-autoproxy />元素,便可啓用對於@AspectJ註解的支持,Spring將自動爲匹配的Bean建立代理,爲了註冊定義好的切面,還要在Spring配置文件中聲明UserBizAdvice的一個實例(不須要被其餘Bean引用,能夠不指定Id屬性);

個人xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>

 

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop

 http://www.springframework.org/schema/aop/spring-aop.xsd

">

<bean id="userserviceimpl" class="cn.cnti.annotation.UserServiceImpl"></bean>

<aop:aspectj-autoproxy />

<bean class="cn.cnti.annotation.UserBizAdvice"></bean>

 ****************************************************************************************************************

</beans>

上一個註解標註加強還能夠這麼用:

@Aspect//@Aspect註解將UserBizAdvice定義爲切面

public class UserBizAdvice2{

@Pointcut("execution(public void save(..))")

public void cut(){

}

 

//前置加強

@Before("cut()")

public void before(){

System.out.println("wo shi UserBizAdvice2");

System.out.println("即將調用業務方法!");

}

//後置加強

@AfterReturning("cut()")

public void afterReturning(){

System.out.println("wo shi UserBizAdvice2");

System.out.println("後置加強");

}

}

其餘不變!

***************************************************************************************************************

使用註解定義其餘類型的加強:

個人註解加強類:

@Aspect//@Aspect註解將UserBizAdvice定義爲切面

public class UserBizAdvice2{

@Pointcut("execution(public void save(..))")

public void cut(){

}

 

//前置加強

@Before("cut()")

public void before(JoinPoint jp){

System.out.println("調用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法入參:"+Arrays.toString(jp.getArgs()));

System.out.println("前置加強");

}

//後置加強

@AfterReturning(pointcut="cut()",returning="returnValue")

public void afterReturning(JoinPoint jp,Object returnValue){

System.out.println("返回值是:"+returnValue);

System.out.println("後置加強");

}

 

@AfterThrowing(pointcut="cut()",throwing="ex")

public void afterThrowing(JoinPoint jp,Exception ex){

System.out.println("異常了:"+ex);

}

//ProceedingJoinPoint是JoinPoint的子接口,它的proceed()方法能夠調用真正的目標方法,從而達到對鏈接點的徹底控制

@Around("cut()")

public Object around(ProceedingJoinPoint pjp) throws Throwable{

System.out.println("環繞前");

Object obj = pjp.proceed();

System.out.println("環繞後");

return obj;

}

//@AspectJ還提供了一種最終加強類型,其特色是不管方法拋出異常仍是正常退出,該加強都會獲得執行,相似於異常處理機制中finally塊的做用,通常用於釋放資源。

@After("cut()")

public void after(){

System.out.println("最終加強!");

}

}

XML同上一個XML沒有變化,惟一注意的一點是:<aop:aspectj-autoproxy />

自動代理默認是對接口的代理,咱們測試的時候:

BeanFactory bf=new ClassPathXmlApplicationContext("annotationContext.xml");

UserService  service = (UserService) bf.getBean("userserviceimpl");

service.save(new User("admin","pwd"));

都是強轉成接口,而後用接口接受,

若是想對類進行代理,能夠這麼設置:

<aop:aspectj-autoproxy proxy-target-class="true"/>

*****************************************************************************************************************

使用Schema配置其餘加強類型:

個人加強類:

public class UserBizAdvice {

public void before(JoinPoint jp){

System.out.println("調用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法入參:"+Arrays.toString(jp.getArgs()));

System.out.println("前置加強");

}

public void afterReturning(JoinPoint jp,Object returnValue){

System.out.println("返回值是:"+returnValue);

System.out.println("後置加強");

}

 

public void afterThrowing(JoinPoint jp,Exception ex){

System.out.println("異常了:"+ex);

}

 

public Object around(ProceedingJoinPoint pjp) throws Throwable{

System.out.println("環繞前");

Object obj = pjp.proceed();

System.out.println("環繞後");

return obj;

}

public void after(){

System.out.println("最終加強!");

}

}

而後個人xml配置:

<?xml version="1.0" encoding="UTF-8"?>

 

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop

 http://www.springframework.org/schema/aop/spring-aop.xsd

">

<bean id="userserviceimpl" class="cn.cnti.schema.UserServiceImpl"></bean>

<bean id="advice" class="cn.cnti.schema.UserBizAdvice"></bean>

<aop:config>

<aop:pointcut expression="execution(* cn.cnti.schema..*.*(..))" id="pointcut"/>

<aop:aspect ref="advice">

<aop:before method="before" pointcut-ref="pointcut"/>

<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="returnValue"/>//和類裏的Object returnValue對應

<aop:after method="after" pointcut-ref="pointcut"/>

<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>

<aop:around method="around" pointcut-ref="pointcut"/>

</aop:aspect>

</aop:config>

</beans>

相關文章
相關標籤/搜索