AOP面向切面的理解

SPRING的主要目的是用来 解偶 提高代码重新性.IOC利用JAVA中的反射机制来生成对象.而AOP是减少面向对象中由于日志或者性能检测而产生的代码的冗余,把冗于的代码用一种代理的方式截取到新的代理类中,对这部分进行集中处理.这有点象树木的年轮一样,我要看这棵树的年轮只要截取其中的一段,然后就知道所有树木段的年轮.
实例
package com.wish.edu;
public interface Waiter {
void greetTo(String name);
void serveTo(String name);
}

package com.wish.edu;
public class NaiveWaiter implements Waiter{
public void greetTo(String name) {
  // TODO Auto-generated method stub
  System.out.println("greet to"+name+"...");
}
public void serveTo(String name) {
  // TODO Auto-generated method stub
  System.out.println("serving "+name+"...");
}
}
实例化出本地服务员

提供"很spring"的方法.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="greetingAdvice" class="com.wish.edu.GreetingBeforeAdvice"></bean>
<bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="proxyInterfaces">
   <value>com.wish.edu.Waiter</value></property>
  <property name="interceptorNames">
   <list>
    <value>greetingAdvice</value>
   </list></property>
  <property name="target" ref="target"></property></bean>
<bean id="target" class="com.wish.edu.NaiveWaiter"></bean>
</beans>

...
    String configPath = "applicationContext.xml";
   ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
   Waiter waiter = (Waiter)ctx.getBean("waiter");
   waiter.greetTo(" John");
...
How are you! Mr . John
greet to John...




package com.wish.edu;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class GreetingBeforeAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object obj) throws Throwable {
  // TODO Auto-generated method stub
  String clientName =(String)args[0];
  System.out.println("How are you! Mr ."+clientName);
//在这里面抽取横面逻辑业务
}
}
前置增强类

package com.wish.edu;
import org.springframework.aop.BeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class TestBeforeAdvice {
public static void main(String[] args) {
  Waiter target = new NaiveWaiter();
  BeforeAdvice advice = new GreetingBeforeAdvice();
  ProxyFactory pf = new ProxyFactory();//代理工厂
  pf.setTarget(target);                //代理目标
  pf.addAdvice(advice);                //前置增强
  Waiter proxy = (Waiter)pf.getProxy();//生成代理
  proxy.greetTo("John");
  proxy.serveTo("Tom");
}
}
//测试类

执行结果是:
How are you! Mr .John
greet toJohn...
How are you! Mr .Tom
serving Tom...

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值