spring 的aop操作,基于aspectj的xml
2018-06-06 本文已影响7人
DouDouZH
实现代码
切点的方法的类Book.java
package work.zhangdoudou.aop;
public class Book {
public void byBook() {
System.out.println("买书--------");
}
}
增强/通知mybook.java
package work.zhangdoudou.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class mybook {
public void before() {
System.out.println("前置增强------------");
}
public void afterReturning() {
System.out.println("后置增强------------");
}
public void after() {
System.out.println("最终增强------------");
}
//环绕通知
public void around(ProceedingJoinPoint point) throws Throwable {
//执行之前
System.out.println("环绕-方法执行之前----");
//执行被增强的方法
point.proceed();
//执行之后
System.out.println("环绕-方法执行之后----");
}
//异常通知
public void afterThrowing() {
System.out.println("异常通知-----------");
}
}
配置文件applicationContext.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-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!--1 配置对象 -->
<bean id="book" class="work.zhangdoudou.aop.Book"></bean>
<bean id="mybook" class="work.zhangdoudou.aop.mybook"></bean>
<!--2 配置aop操作 -->
<aop:config>
<!-- 2.1配置切入点 -->
<aop:pointcut expression="execution(* work.zhangdoudou.aop.Book.*(..))" id="pointcut1"/>
<!-- 2.2配置切面 把增强用到方法上 -->
<aop:aspect ref="mybook">
<!-- 配置增强类型 增强类里哪一个作为前置增强 -->
<!-- 前置增强 -->
<aop:before method="before" pointcut-ref="pointcut1"/>
<!-- 后置增强 -->
<aop:after-returning method="afterReturning" pointcut-ref="pointcut1"/>
<!-- 最终增强 -->
<aop:after method="after" pointcut-ref="pointcut1"/>
<!-- 环绕通知 -->
<aop:around method="around" pointcut-ref="pointcut1"/>
<!-- 异常通知 -->
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
</beans>
测试类Test1.java
package work.zhangdoudou.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import work.zhangdoudou.aop.Book;
public class Test1 {
@Test
public void test() {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Book book=(Book)context.getBean("book");
book.byBook();
}
}