您的位置:首页 > 编程语言 > Java开发

spring学习(七)—AOP通过配置文件方式实现

2017-02-10 17:29 886 查看
转自传智博客学习视频

主要包括:通过xml文件进行前置增强,后置增强,环绕增强的具体样例

代码价构:



1.配置文件

<?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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

<bean id="book" class="aop.Book"></bean>
<bean id="myBook" class="aop.MyBook"></bean>

<aop:config>
<!-- 1.配置切入点 -->
<aop:pointcut expression="execution(* aop.Book.*(..))" id="pointcut1"/>
<!-- 2.配置切面,将增强用到方法上面 -->
<!-- 指定增强类 -->
<aop:aspect ref="myBook">
<!-- 配置增强类型 ,method:增加的类中使用哪个方法进行前置增强,pointcut-ref:增强用到哪个切入点上-->
<aop:before method="before1" pointcut-ref="pointcut1"/>
<!--   后置增强 -->
<aop:after method="after1" pointcut-ref="pointcut1"/>
<aop:around method="around1" pointcut-ref="pointcut1"/>
</aop:aspect>

</aop:config>
</beans>


2.被增强类

package aop;

public class Book {

public void add(){
System.out.println("add.........");
}

}


3.增强类

package aop;

import org.aspectj.lang.ProceedingJoinPoint;

public class MyBook {

public void before1() {
System.out.println("前置增强");
}

public void after1() {
System.out.println("后置增强");
}

public void around1(ProceedingJoinPoint proceedingJoinPoint)
throws Throwable {
// 环绕通知:方法之前
System.out.println("环绕通知:方法之前");

// 执行被强的方法
proceedingJoinPoint.proceed();

// 环绕通知:方法之后
System.out.println("环绕通知:方法之后");

}
}


4.测试类

package aop;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAop {

@Test
public void testBook(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Book book = (Book) context.getBean("book");
book.add();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: