1、配置文件(文件名没有规定,可任意命名)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.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-3.0.xsd">
<!-- 开启自动扫描Bean -->
<context:component-scan base-package="com.zh.aop" />
<!-- 开启AOP注解支持 -->
<aop:aspectj-autoproxy />
</beans>
2、创建实现类
/**
*日志记录实现类 (基于注解的AOP)
*/
@Aspect //声明切面类
@Component
public class LogAspect {
//前置增强
@Before("execution(* com.zh.aop.*.*(..))") //用于匹配需要加入增强的方法
public void beforeAdvice(JoinPoint joinpoint) throws Throwable{
//填写前置增强代码
System.out.println("这是前置增强===========");
//获取目标对象包全名
String classType=joinpoint.getTarget().getClass().getName();
Class<?>clazz=Class.forName(classType);
String clazzName=clazz.getName();
System.out.println("这是目标对象包全名:"+clazzName);
//获取目标对象类名
String clszzSimplName=clazz.getSimpleName();
System.out.println("这是目标对象类名:"+clszzSimplName);
//获取目标对象方法参数值
Object [] args=joinpoint.getArgs();
System.out.println("这是目标对象方法参数值:"+args[0]);
}
//后置增强
@After("execution(* com.zh.aop.*.*(..))")
public void afterAdvice() {
//填写前置增强代码
System.out.println("这是后置增强===========");
}
//环绕增强
@Around("execution(* com.zh.aop.*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable{
//填写前置增强代码
System.out.println("这是环绕增强(前)");
Object object=joinPoint.proceed();
//填写后置增强代码
System.out.println("这是环绕增强(后)");
return object;
}
//抛出异常增强
@AfterThrowing(pointcut="execution(* com.zh.aop.*.*(..))",throwing="ex")
public void throwAdvice(Exception ex) {
System.out.println("抛出异常增强");
System.out.println(ex.getMessage());
}
}
3、如何使用
@Component
public class AnnotationTest {
public static void main(String[] args) {
//加载配置文件
ApplicationContext applicationContext
=new ClassPathXmlApplicationContext("com/zh/aop/annotation/aopannotation.xml");
//通过IOC容器实现反转,把控制权交给容器,通过容器来创建对象,让三层架构之间的耦合性降低
//创建具体实现类
IForumService forumService=(IForumService) applicationContext.getBean("forumServiceImpl");
//调用实现类的方法,加入增强
forumService.removeForun(2);
//forumService.removeForun(2);
}
}