1.添加类库:aspectjrt.jar和aspectjweaver.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
com.springsource.org.aspectj.tools-1.6.6.RELEASE.jar
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.7.1</version>
</dependency>
2.添加aop schema.
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
3.定义xml元素:<aop:aspectj-autoproxy>4.编写java类,并用@Aspect注解成通知,AspectJ 支持 5 种类型的通知注解:
@Before: 前置通知, 在方法执行之前执行
@After: 后置通知, 在方法执行之后执行
@AfterRunning: 返回通知, 在方法返回结果之后执行
@AfterThrowing: 异常通知, 在方法抛出异常之后
@Around: 环绕通知, 围绕着方法执行
配置成普通bean元素即可.
前置通知:@Before
@Aspectpublic class MyAspectjAdvice {@Before("execution(* WelcomeService.*(..))")
public void sayHello(){..}
@Before("execution(* WelcomeService.*(..))")
public void sayHello(JoinPoint jp){..}
JoinPoint参数可访问连接点细节,入方法名和参数等.
jp.getTarget()jp.getThis()
jp.getArgs()
jp.getSignature().getName()
后置通知:@After
@After("execution(* *..WelcomeService.*(..))")
public void sayBye(){..}
后置通知在目标方法执行完成之后执行.一个切面aspect包含很多通知.
@After 后置通知表明目标方法执行完之后,不论是否抛异常,都会织入该通知.
@AfterReturning 方法返回后通知只在目标方法返回以后执行,若抛异常不执行.
@AfterReturning(pointcut="",returning="res")
public void xxx(Joinput jp,Object res)
在后置通知中可接收到返回值.res即是用来接收返回值的对象.
环绕通知:@Around
@Around("execution(* *..WelcomeService.*(..))")public void around(ProceedingPointCut jp){..}
注意:可以控制目标方法是否调用,以及返回完全不同的对象,要慎用.
指定优先级:
@Aspect@Order(0)
public class xxx{...}
加上@Order注解可以指定加入切面的优先级(先后顺序,值越小,优先级越高)
重用切入点定义:
将切入点注解到一个空的方法体上,其它地方引用即可.//定义切入点
@Pointcut("execution(* *..WelcomeService.*(..))")
public void performPoint(){}
@Before("performPoint()")
@After("performPoint()")
demo
/**
* 观众(切面)
*/
@Aspect
public class Audience {
@Pointcut(value="execution(* study.spring.aop.aspectj.Performer.*(..))")
public void watch() {}
// interface ModeifyDate method set get
@DeclareParents(value="study.spring.aop.aspectj.Singer",
defaultImpl=ModifyDateImpl.class)
public ModifyDate md ;
@Before(value="watch()")
public void setting() {
System.out.println("@Before大批观众正在接近,入场就坐");
}
@Before(value="watch()")
public void turnOffCellphone() {
System.out.println("@Before关闭手机");
}
@AfterThrowing(pointcut="watch()",throwing="e")
public void hiss(Exception e) {
System.out.println("@AfterThrowing出事了"+e.getMessage());
}
@AfterReturning(pointcut="watch()",returning="ret")
public void applaud(Object ret) {
if(ret instanceof Boolean) {
if((Boolean)ret) {
System.out.println("@AfterReturning演的太好了,鼓掌....");
}
else {
System.out.println("@AfterReturning演的太差了,嘘声,扔苹果...");
}
}else{
System.out.println("@AfterReturning观众正在观看节目...");
}
}
@After("watch()")
public void goHome() {
System.out.println("@After节目演完,观众回家");
}
}
/**
* 演员
*/
public interface Performer {
public boolean show();
}
public class Singer implements Performer{
public boolean show() {
int nextInt = new Random().nextInt(3);
if(nextInt==2)throw new RuntimeException("歌手昏倒了 ");
String str= nextInt==0?"看上去状态很好":"这TMD什么破嗓子!!!";
System.out.println("唱歌中...啦啦啦啦..."+str);
if(nextInt==0) return true;
else return false;
}
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!-- 观众 -->
<bean id="audience" class="study.spring.aop.aspectj.Audience"></bean>
<!-- 歌手 -->
<bean id="singer" class="study.spring.aop.aspectj.Singer"></bean>
<!-- 使用自动代理 -->
<aop:aspectj-autoproxy/>
</beans>
public class AspectjAppDrive {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("study/spring/aop/aspectj/aspectj.xml");
Performer bean = (Performer)ac.getBean("singer");
bean.show();
ModifyDate md = (ModifyDate)bean;
md.setDate(new Date());
System.out.println(md.getDate());
}
result:1@Before大批观众正在接近,入场就坐
@Before关闭手机
唱歌中...啦啦啦啦...看上去状态很好
@AfterReturning演的太好了,鼓掌....
@After节目演完,观众回家
---------------------------------------------------
result:2
@Before大批观众正在接近,入场就坐
Exception in thread "main" java.lang.RuntimeException: 歌手昏倒了
@Before关闭手机
@AfterThrowing出事了歌手昏倒了
@After节目演完,观众回家
Exception in thread "main" java.lang.RuntimeException: 歌手昏倒了
@Before关闭手机
@AfterThrowing出事了歌手昏倒了
@After节目演完,观众回家
--------------------------------------------------
result:3
@Before大批观众正在接近,入场就坐
@Before关闭手机
唱歌中...啦啦啦啦...这TMD什么破嗓子!!!
@AfterReturning演的太差了,嘘声,扔苹果...
@After节目演完,观众回家
@Before关闭手机
唱歌中...啦啦啦啦...这TMD什么破嗓子!!!
@AfterReturning演的太差了,嘘声,扔苹果...
@After节目演完,观众回家