一、创建需要增强的类User
package com.Spring5.AOP;
import org.springframework.stereotype.Component;
@Component(value = "user111")
public class User {
public void add(){
System.out.println("add ... .. ...");
}
}
二、创建增强类(编写增强逻辑)
package com.Spring5.AOP;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Aspect
public class UserProxy {
@Before(value = "execution(* com.Spring5.AOP.User.add())")
public void bf(){
System.out.println("前置通知 ... .. .. ");
}
@AfterReturning(value = "execution(* com.Spring5.AOP.User.add())")
public void af(){
System.out.println("后置通知 ... .. .. ");
}
@Around(value = "execution(* com.Spring5.AOP.User.add())")
public void hr(ProceedingJoinPoint p) throws Throwable{
System.out.println("环绕通知前 ... .. .. ");
p.proceed();
System.out.println("环绕通知后 ... .. .. ");
}
@AfterThrowing(value = "execution(* com.Spring5.AOP.User.add())")
public void aft(){
System.out.println("异常通知 ... .. .. ");
}
@After(value = "execution(* com.Spring5.AOP.User.add())")
public void fina(){
System.out.println("最终通知 ... .. .. ");
}
}
三、进行通知的配置(需要在配置文件中引入context和aop命名空间)
1、在Spring配置文件中开启注解扫描
<context:component-scan base-package="com.Spring5.AOP"></context:component-scan>
2、使用注解创建增强类和被增强类的对象
利用@Component
3、在增强类上方添加@Aspect
@Aspect
用来表示这是一个增强类
4、在Spring配置中生成对象
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
四、配置不同类型的通知
1、在通知类里作为通知的方法上面添加通知类型注解,使用切入点表达式配置
- 前置通知
@Before
- 后置通知
@AfterReturning
- 环绕通知
@Around
- 异常通知
@AfterThrowing
- 最终通知
@After
- 切入点表达时示例
@Before(value = "execution(* com.Spring5.AOP.User.add())")
,具体写法在上一篇文章有提到
五、测试
xml配置文件如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="com.Spring5.AOP"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
测试类如下
package com.Spring5.TestSpring;
import com.Spring5.AOP.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAOP {
@Test
public void testaop(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
User user=context.getBean("user111",User.class);
user.add();
}
}