读书人

AOP的兑现

发布时间: 2012-10-29 10:03:53 作者: rapoo

AOP的实现
1.先做一个接口 里有 foo()方法
?package com.lily.rules;
?public interface IUserDAO {
??public void foo();
?}
2.在做一个实现接口的类
?package com.lily.rules;

?public class UserDAOImp implements IUserDAO {
?public void foo() {//固定的方法
??// TODO Auto-generated method stub
??System.out.println("hello first");
?}

?}
3.做一个测试类
?package com.lily.rules;
?import org.springframework.context.ApplicationContext;
?import org.springframework.context.support.FileSystemXmlApplicationContext;
?public class MainApplication {
?public static void main(String args[]){
??ApplicationContext? txt = new FileSystemXmlApplicationContext??

("D:\\workspace\\FirstSample\\com\\lily\\rules\\applicationContext.xml");
??IUserDAO? log??? = (IUserDAO) txt.getBean("businesslogicbean");
??log.foo();
?}
?}


?}
4.做一个Before类:固定的类名和实现的接口
?package com.lily.rules;
?import java.lang.reflect.Method;
?import org.springframework.aop.MethodBeforeAdvice;
?public class TracingBeforeAdvice implements MethodBeforeAdvice {

?public void before(Method arg0, Object[] arg1, Object arg2)
???throws Throwable {
??// TODO Auto-generated method stub
??System.out.println(" hello before");
?}

?}
5.开始做After类:固定的类名和实现的接口
?package com.lily.rules;
?import java.lang.reflect.Method;
?import org.springframework.aop.AfterReturningAdvice;
?public class TracingAfterAdvice implements AfterReturningAdvice {

?public void afterReturning(Object arg0, Method arg1, Object[] arg2,
???Object arg3) throws Throwable {

????????? System.out.println("hello after");

?}
6.做配置信息 applicationContext.xml文件
<beans></beans>
一个完整的切面操作代码完成了!!

1 楼 Angelialily 2007-09-04 不好意! 不知道为什么 发出去的文章少了一些代码. 下面的代码在AOP实现二里补充.!!! 抱歉,抱歉, 2 楼 Angelialily 2007-09-04 不好意思.配置文件发表不出来了 不知道为什么带标签的东西它解释出的是乱码! 3 楼 梦杀杀 2007-09-07 楼主用附件上传不就是咯~.~ 4 楼 yeshucheng 2007-09-08 不知道LZ发这个的用意是什么?:)不明白 5 楼 jerry_lee 2007-09-10 代理机制 6 楼 yongyuan.jiang 2007-09-12 spring aop在spring类初始化时候便生成一个代理类,大致提供以下功能:
beforeMethod
afterMethod
roundMethod
原Method

调用这个类时先检查代理对象,判断是否有aop方法,有则根据先后顺序,执行aop方法。
如果没有,直接执行方法。


7 楼 allen_java 2007-12-26 还行 大体流程描述出来了 8 楼 colin2wang 2008-01-30 不错,是那么一会儿事

读书人网 >软件架构设计

热点推荐