您的位置:首页 > 运维架构

来理解AOP中的"通知"

2009-03-29 10:44 344 查看
首先解释一下概念:
AOP:面向方面编程
通知:分为 前置通知,后置通知,环绕通知,异常通知
此处以前置通知为例,它的意思 就是在业务代码执行前要执行的方法 这个理解很含糊,此处待编辑......

看实例:

1.定义一个接口
public interface BookService {
public boolean buy(String userName,String bookName,double price);
public void comment(String userNmae,String comments);
}

2.编写实现类
public class BookServiceImpl implements BookService {
public boolean buy(String userName, String bookName, double price) {
System.out.println("业务方法buy开始执行");
System.out.println("*"+userName+" buy books: "+bookName);
System.out.println("*"+userName+" add points "+(int)(price/10));
System.out.println("*向物流系统下发订单");
System.out.println("业务方法buy结束执行");
return true;
}
public void comment(String userName, String comments) {
System.out.println("业务方法comment开始执行");
System.out.println("*"+userName+" release comment: "+comments);
System.out.println("业务方法comment结束执行");
}
}

3.编写“通知”代码(方面代码)
public class LoginAdvice implements MethodBeforeAdvice {
private static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

public void before(Method method, Object[] arg1, Object obj) throws Throwable {
System.out.println("/n[系统日志]["
+sdf.format(new java.util.Date())+"]"
+method.getName()
+"("+arg1.toString()+")");
}
}

4.编写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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="bookServiceTarget" class="com.chap8.BookServiceImpl"></bean>
<bean id="logAdvice" class="com.chap8.LoginAdvice"></bean>
<bean id="bookService" class="org.springframework.aop.framework.ProxyFactoryBean">
<!--proxyInterfaces 表示被代理的接口-->
<property name="proxyInterfaces">
<value>com.chap8.BookService</value>
</property>
<!--interceptorNames 表示织入的通知列表-->
<property name="interceptorNames">
<list>
<value>logAdvice</value>
</list>
</property>
<!--target 表示被代理的原Bean-->
<property name="target" ref="bookServiceTarget"></property>
</bean>
</beans>

5.编写测试类
public class AopTest {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService)context.getBean("bookService");
bookService.buy("小明", "十万个为什么", 15.8);
bookService.comment("小虎", "好多好的");
}
}

6.运行结果
[系统日志][2009-03-29 10:06:24]buy([Ljava.lang.Object;@8238f4)
业务方法buy开始执行
*小明 buy books: 十万个为什么
*小明 add points 1
*向物流系统下发订单
业务方法buy结束执行

[系统日志][2009-03-29 10:06:24]comment([Ljava.lang.Object;@297ffb)
业务方法comment开始执行
*小虎 release comment: 好多好的
业务方法comment结束执行

方面代码被无缝的接入程序了,是不是很方便?

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