前往顾页
以后地位: 主页 > 收集编程 > Jsp实例教程 >

深度剖析Spring中的AOP学习教程

时候:2012-10-07 23:08来源:知行网www.zhixing123.cn 编辑:麦田守望者

1、定义一个接口

package springdemo.aop.beforeAdvsXml;

 

public interface Writer {

void greetTo(String name);

void serveTo(String name);

}

 

2、定义一个实现类

package springdemo.aop.beforeAdvsXml;

 

public class NativeWriter implements Writer {

public void greetTo(String name) {

System.out.println("greeting to "+name+" ...");

}

public void serveTo(String name) {

System.out.println("greeting to "+name+" ...");

}

}

 

3、定义一个切入体例

package springdemo.aop.beforeAdvsXml;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

 

public class GreetingBeforeAdvs implements MethodBeforeAdvice {

public void before(Method arg0, Object[] arg1, Object arg2)

throws Throwable {

String clientName=(String)arg1[0];

System.out.println("How are you ! Mr."+clientName+".");

}

}

 

4、接上去可利用两种体例来进行测试,其一是经由过程代码进行装配测试,其二是经由过程XML进行装配测试。

 

解析Spring中的AOP - 游目骋怀 - 游目骋怀

 

1)经由过程代码装配

package springdemo.aop.beforeAdvs;

import org.springframework.aop.BeforeAdvice;

import org.springframework.aop.framework.ProxyFactory;

 

public class TestBeforeAdvs {

public static void main(String [] args)

{

Writer target=new NativeWriter();

BeforeAdvice advs=new GreetingBeforeAdvs();

ProxyFactory pf=new ProxyFactory();

pf.setTarget(target);

pf.addAdvice(advs);

Writer proxy=(Writer)pf.getProxy();

proxy.greetTo("John");

proxy.serveTo("Tom");

}

}

 

 

2)经由过程XML装配

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" >

<beans>

<bean id="writer" class="org.springframework.aop.framework.ProxyFactoryBean">

<property name="proxyInterfaces" value="springdemo.aop.beforeAdvsXml.Writer" />

<property name="interceptorNames">

<list>

<value>greetingAdvice</value>

</list>

</property>

<property name="target" ref="target" />

</bean>

<bean id="target" class="springdemo.aop.beforeAdvsXml.NativeWriter"/>

<bean id="greetingAdvice" class="springdemo.aop.beforeAdvsXml.GreetingBeforeAdvs" />

</beans>

测试体例:

package springdemo.aop.beforeAdvsXml;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

 

public class TestBeforeAdvsXml {

public static void main(String [] args)

{

String[] configPath={"/App_Cfg/beforeAdvsXml.xml"};

ApplicationContext ctx=new FileSystemXmlApplicationContext(configPath);

Writer writer=(Writer)ctx.getBean("writer");

writer.greetTo("John");

}

}

 

顶一下
(1)
100%
踩一下
(0)
0%
------分开线----------------------------
标签(Tag):Java JAVA实例教程 JAVA根本教程 Java源代码 Java技能
------分开线----------------------------
颁发评论
请自发遵循互联网相关的政策法规,严禁公布色情、暴力、革命的谈吐。
评价:
神色:
考证码:点击我更换图片
猜你感兴趣