上一篇中用XMLSchema配置方式介紹了簡單日志實現(xiàn),這里再用annotation來介紹
(注意是spring2.0)
來看接口,這個接口簡單的不能再簡單了,嘻嘻。
public interface Hello {
String hello(String name);
}
實現(xiàn)類:
public class SayHello implements Hello {
public String hello(String name) {
String result = "---hello " + name;
System.out.println(result);
return result;
}
}
切面,里面采用了annotation來注釋,也說明了大概意思:
/*
* Create Date:2008-11-20 下午03:09:11
*
* Author:dingkm
*
* Version: V1.0
*
* Description:對進(jìn)行修改的功能進(jìn)行描述
*
*
*/
//首先這是注釋這個類就是切面
@Aspect
public class MyAspect {
//這里是注釋要切入的方法,AfterReturning是表示方法返回以后進(jìn)行切入,我這里
//選這個的話是因為日志一般都是在方法執(zhí)行完成后記錄,當(dāng)然你可以拿Before來試
@AfterReturning("execution(* *.aspectJ.*.hello(..))")
public void doLog(ProceedingJoinPoint joinpoint) throws Throwable{
String result = (String)joinpoint.proceed();
System.out.println("---doLog"+result);
}
}
下面是spring配置文件,這里的配置文件就比較簡單了:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<!--基于@AspectJ切面的驅(qū)動器,如果沒有這句話 切面的代碼是不會執(zhí)行的,可以試下-->
<aop:aspectj-autoproxy/>
<!--這個bean是作為切面 -->
<bean id="myAspect" class="spring2aop.aspectJ.MyAspect"></bean>
<!--要織入代碼的bean-->
<bean id="hello" class="spring2aop.aspectJ.SayHello"></bean>
</beans>
<aop:aspectj-autoproxy/>這句很關(guān)鍵哦
再來看測試類:
public class Test {
/**
* @Description 方法實現(xiàn)功能描述
* @param args
* void
* @throws 拋出異常說明
*/
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext(
"applicationContext21.xml");
Hello h = (Hello)act.getBean("hello");
h.hello("laoding");
}
}
看看結(jié)果:
---hello laoding
---hello laoding
---doLog---hello laoding
---hello laoding這個與上一篇文章中提到的道理一樣,因為記錄日志要取得返回結(jié)果,所以執(zhí)行了兩次
最后的那句就是我們要的,這樣就達(dá)到了記錄日志的目的,哈哈,收工回去看PPS中韓魔獸對抗。
posted on 2008-11-25 18:27
老丁 閱讀(1729)
評論(0) 編輯 收藏 所屬分類:
spring