1.被代理的类
public interface Aop {
void add();
}
@Component("aopImplement")
public class AopImplement implements Aop{
@Override
public void add() {
System.out.println("我是add已经存在的功能");
}
}
2.代理类(Before,After,AfterThrowing,AfterReturning,Around)
@Component
@Aspect
public class AopAddClass {
@Before("execution(* test10month.test1014.AopImplement.add(..))")
public void beFore() {
System.out.println("我是before");
}
@After("execution(* test10month.test1014.AopImplement.add(..))")
public void after() {
System.out.println("我是after");
}
@AfterThrowing("execution(* test10month.test1014.AopImplement.add(..))")
public void afterThrowing() {
System.out.println("我是afterThrowing");
}
@AfterReturning("execution(* test10month.test1014.AopImplement.add(..))")
public void afterReturning() {
System.out.println("我是afterReturning");
}
@Around("execution(* test10month.test1014.AopImplement.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("我是around前");
proceedingJoinPoint.proceed();
System.out.println("我是around后");
}
}
3.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: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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="test10month.test1014"/>
<!--
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。
如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。
如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理将起作用。
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
4.测试类
public class Test1014 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10month/test1014/AOP.xml");
AopImplement bean = context.getBean("aopImplement", AopImplement.class);
bean.add();
}
}