步骤
1.导入jar包:
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aop-4.2.4.RELEASE.jar
spring-aspects-4.2.4.RELEASE.jar
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
2.在配置文件中加入aop 的命名空间
xmlns:aop=“http://www.springframework.org/schema/aop”
3.基于注解的方式
a.在配置文件中加入如下配置:
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.atguigu.spring.aop.impl"></context:component-scan>
<!-- 使用AsoectJ 注解起作用:自动匹配的类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
b.把横切关注点的代码抽象到切面的类中
i.首先是需要把该类放入到IOC容器中,即加入@Component 注解
ii.切面还需要加入@Aspect 注解
@Aspect
@Component
public class LoggingAspect {
}
c.在类中声明各种通知
i.声明一个方法
ii.在方法前加入一个@Before/@After/@Around/@AfterReturning/@AfterThrowing 注解
- 前置通知@Before
@Aspect
@Component
public class LoggingAspect {
//声明该方法是一个前置通知,在目标方法之前执行
@Before("execution(* com.atguigu.spring.aop.impl.*.*(..))")
public void beforeMethod() {
System.out.println("The method begins");
}
}
d.可以在通知方法中声明一个类型为 JoinPoint 的参数,然后就能访问链接细节,入方法名称和参数值
@Aspect
@Component
public class LoggingAspect {