现在的位置: 首页 > 综合 > 正文

Spring_AOP_0200_XML入门

2016年09月01日 ⁄ 综合 ⁄ 共 2432字 ⁄ 字号 评论关闭

进行完annotation的测试之后,立马进行了xml方式的测试,重新用0100工程复制新的一个工程,命名为:Spring_AOP_0200_XML

把其中的所有关于spring,aspectj annotation去掉(保留@Override注解)

有礼貌的服务生代理类改成如下形式:

package com.aop.proxy;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * @author 紫竹
 * 礼貌的服务生代理:在打招呼之前说一声hello,服务的时候记录时间,结束后say:good bye, have a good day
 */
public class NiceWaiterProxy {
	
	public void before(){
		System.out.print("hello , ");
	}
	
	public void after(){
		System.out.print("have a good day!!!");
	}
	
	public void around(ProceedingJoinPoint pjp){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
		System.out.println("I am a clock , record: " + sdf.format(new Date()) );
		try {
			pjp.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println("I am a clock , record: " + sdf.format(new Date()) );
	}
	
}

然后将annotation的方式改成xml方式,修改beans.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" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

	<!-- 将需要用spring 初始化的bean全部配上 -->
	<bean id="naiveWaiter" class="com.aop.impl.NaiveWaiter"></bean>
	<bean id="niceWaiterProxy" class="com.aop.proxy.NiceWaiterProxy"></bean>

	<aop:config>
		<!-- 定义一个切面,id="myAspect" 没用到,将com.aop.proxy.NiceWaiterProxy类声明为切面类 -->
		<aop:aspect id="myAspect" ref="niceWaiterProxy">
			<!-- 声明连接点,声明在哪些类的哪些方法上需要进行切面  -->
			<aop:pointcut id="greet" expression="execution(* com.aop..greetTo(..))" />
			<aop:pointcut id="server" expression="execution(* com.aop..server*(..))" />
			<aop:pointcut id="bye" expression="execution(* com.aop..bye(..))" />
			<!-- 织入,在哪个连结点织入,是在连结点之前,之后,还是前后都需要 -->
			<aop:before pointcut-ref="greet" method="before" />
			<aop:around pointcut-ref="server" method="around" />
			<aop:after pointcut-ref="bye" method="after" />
		</aop:aspect>
	</aop:config>

</beans>

运行测试类,输出结果:

hello , greet to Jonhe....
I am a clock , record: 2011-30-11 23:30:13
server to ....
I am a clock , record: 2011-30-11 23:30:13
bye !
have a good day!!!

很好,测试结束!

抱歉!评论已关闭.