基于注解的AOP配置
1、新建新项目,在pom.xml文件当中新增加以下依赖:
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
2、新建bean.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
3、配置Spring创建容器时所要扫描的包。
<context:component-scan base-package="包名"></context:component-scan>
4、在业务层实现类的上方,添加:
5、将通知类交给Spring来管理,配置Logger类,在其上方添加:
6、对Logger类当中各个通知方法的通知类型进行配置,在各种方法上面添加注解。
前置通知 @Before()
后置通知 @AfterReturning()
异常通知 @AfterThrowing()
最终通知 @After()
环绕通知 @Around()
7、配置切入点表达式。定义一个方法,在方法上方使用@pointcut来指定切入点表达式。表达式的内容和在xml文件中配置的规定相同。
8、配置Spring开启注解aop的支持。在bean.xml文件当中,添加:
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
9、在第六步的基础上往括号里添加关联,将第七步的“方法名()”添加到括号里。
10、不使用xml的配置方式
添加注解:@EnableAspectJAutoProxy