posts - 431,  comments - 344,  trackbacks - 0

接口
package com.rain.bean;

public interface Bean {
 public void theMethod();
}

JavaBean
package com.rain.bean;

public class BeanImpl implements Bean {

 public void theMethod() {
  // TODO Auto-generated method stub
  System.out.println(this.getClass().getName()+"."+new Exception().getStackTrace()[0].getMethodName()+"()"+"Says Hello!");
 }
}

MethodBeforeAdvice
package com.rain.bean;

import Java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class TestBeforeAdvice implements MethodBeforeAdvice {

 public void before(Method arg0, Object[] arg1, Object arg2)
   throws Throwable {
  // TODO Auto-generated method stub
  System.out.println("Hello world! (by "+this.getClass().getName()+")");
 }
}

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<!--CONFIG-->
   <bean id="bean" class="org.springframework.aop.framework.ProxyFactoryBean">
     <property name="proxyInterfaces">
       <value>com.rain.bean.Bean</value>
     </property>
     <property name="target">
       <ref local="beanTarget"/>
     </property>
     <property name="interceptorNames">
       <list>
         <value>theAdvisor</value>
       </list>
     </property>
   </bean>
<!--CLASS-->
   <bean id="beanTarget" class="com.rain.bean.BeanImpl"></bean>
<!--ADVISOR-->
   <bean id="theAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
     <property name="advice">
       <ref local="theBeforeAdvice"/>
     </property>
     <property name="pattern">
       <value>com\.rain\.bean\.Bean\.theMethod</value>
     </property>
   </bean>
<!--ADVICE-->
   <bean id="theBeforeAdvice" class="com.rain.bean.TestBeforeAdvice"></bean>
</beans>

Test
package com.rain.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rain.bean.Bean;

public class TestAOP {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
  Bean x=(Bean)ctx.getBean("bean");
  x.theMethod();
 }
}

结果:
Hello world! (by com.rain.bean.TestBeforeAdvice)
com.rain.bean.BeanImpl.theMethod()Says Hello!


posted on 2006-09-25 08:47 周锐 阅读(164) 评论(0)  编辑  收藏 所属分类: Spring

只有注册用户登录后才能发表评论。


网站导航: