(1)spring注解配置
配置文件开启aop
<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: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/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">
<aop:aspectj-autoproxy/>//自动代理
注解
切面@Aspect+四个注解 @Before @AfterReturning @AfterThrowing@After
切面@Aspect+@Arround
注解中的值为切点(需要增强类的方法)
示例:
@Component
@Aspect
public class Advice {
public void writeLog(){
System.out.println("写一个开发备忘录");
}
//try{ }
@Before("execution( * com.wzx.service..*.*(..))")
public void before(){
System.out.println("before-------");
}
@AfterReturning("execution( * com.wzx.service..*.*(..))")
public void afterReturn(){
System.out.println("afterReturn-------");
}
//catch(exception e){ }
@AfterThrowing("execution( * com.wzx.service..*.*(..))")
public void afterThrow(){
System.out.println("afterThrow-------");
}
//finally
@After("execution( * com.wzx.service..*.*(..))")
public void after(){
System.out.println("after-------");
}
------------------------------------------------------------------------
around配置等于上面的配置
@Around("execution( * com.wzx.service..*.*(..))")
public void arround(ProceedingJoinPoint point ){//参目标类中的任意方法
try{
//执行before
before();
System.out.println("arround-------");
point.proceed();
//执行正常返回
afterReturn();
}catch (Throwable e){
//补救方法
afterThrow();
}finally {
//释放资源的方法
after();
}
}
}