AOP的使用
1.需要引入aspectJ的jar包。
2.在配置文件中 配置自动扫描和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-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 在配置文件中配置组件扫描 -->
<context:component-scan base-package="com.test" />
<!-- 在配置文件中配置aop自动代理 -->
<aop:aspectj-autoproxy />
</beans>
3.定义切面
@Component
@Aspect //定义切面
public class Broker {
// 前置通知
// 当执行到响应的代码的时候,就会触发切面中的代码 @Before表示在相应方法之前执行。
@Before("execution(public void signContract())")
public void look() {
System.out.println("看看");
}
// 后置通知
@After(value = "execution(public * *(..))")
public void live() {
System.out.println("住住");
}
}
@Component
@Aspect //定义切面
public class Broker {
//环绕通知
@Around("execution(public void signContract())")
public void around(ProceedingJoinPoint joinPoint) {
System.out.println("啦啦啦 ");
try {
// 可以控制 被拦截的方法 执不执行,执行的顺序
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4.相应的语法
在通知中通过value属性定义切点
•通过execution函数,可以定义切点的方法切入
•语法:
–execution(<访问修饰符>?<返回类型><方法名>(<参数>)<异常>)
•例如
–匹配所有类public方法 execution(public * *(..))
–匹配指定包下所有类方法 execution(* com.imooc.dao.*(..))
-不包含子包–execution(* com.imooc.dao..*(..)) ..*表示包、子孙包下所有类
–匹配指定类所有方法 execution(* com.imooc.service.UserService.*(..))
–匹配实现特定接口所有类方法 execution(* com.imooc.dao.GenericDAO+.*(..))
–匹配所有save开头的方法 execution(* save*(..))