基本的概念在前面已经介绍过了,可以传送门
这里就讲讲名词解释和演示代码
一.名词解释
1.连接点 : joinpoint ,在spring中指要被拦截的方法(允许你使用通知的地方)
2.通知 : Advice ,在拦截到joinpoint以后所要采取的操作(异常处理,前/后置通知) ,也就是前文我们所说的日志等与业务逻辑无关的功能
3.切入点 : pointcut ,可以直接拦截某一层的所有方法,我把它理解为连接点的加强,joinpointPlus
4.切面 : Aspect ,通知和切入点的结合
秉承着遇事不决思维导图的原则
灵感来源
二.通知的分类和应用
1.前/后置通知 : @Before("方法") @After("方法")
,调用注解方法的前后都会调用参数中的方法
2.异常通知 : @AfterThrowing
配合Logger类打印日志到控制台或文件
3.环绕通知 : @Around
,可以用作方法的性能分析,但是要求不能出异常
代码统一在第四目给出
三.基于注解方式声明切面的基本步骤
1.在xml配置文件中声明`<aop:aspectj-autoproxy/>`
2.拷贝约束
3.拷贝jar包并使用@Aspect通过注解方式开启AOP
4.使用@pointcut切所有方法(不一定就要切所有方法,也可以挑几个切)
5.前/后置通知(即除业务逻辑外的代码)
带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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
">
四.代码
讲了一大堆,真的不如直接上代码来的实在
我们写这么多代码,把类注册到容器中是代码能够正常运行的前提条件
配置文件
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.hzyc.lesson">
</context:component-scan>
**这里要特别强调,Logger在引包时,应该引import org.apache.log4j.Logger;
日志打印功能
@Component
@Aspect
public class Logging {
Logger log= Logger.getLogger(Logging.class);
//定义一个日志对象
@Pointcut("execution(* com.hzyc.lesson.service.*.*(..))")
//切service所有方法
public void test() {
}
@Before("test()")
public void before() {
System.out.println("前置通知");
}
@After("test()")
public void after() {
System.out.println("后置通知");
}
@AfterThrowing(pointcut="test()",throwing = "ex")
public void afterThrowingAdice(Exception ex) { //抛出异常
// int i = 1/0;
System.out.println("异常 : "+ex.toString()); //输出异常
log.error("异常通知",ex);
}
@Around("test()")
public Object aroundAdvice(ProceedingJoinPoint pjp)
throws Throwable {
long start = System.currentTimeMillis();
Object obj = pjp.proceed();//执行
long end = System.currentTimeMillis();
log.info(pjp.getSignature() + "方法执行时间:"
+ (end - start) + ".ms");
return obj;
}
}
最后在讲一讲关于日志打印的问题
有些编译器是无法直接查看jar包的原码的,因此需要下载一个插件jd-eclipse
在log4j.properties文件中 ,可以通过调整FileAppender将日志打印到text文件里去