你的位置:首页 > Java教程

[Java教程]spring AOP 简单入门案例


TestServiceinter.java

1 package com.frank.aop;2 3 public interface TestServiceinter {4   public void SayHello();5 6 }

TestServiceImp.java

 1 package com.frank.aop; 2  3 public class TestServiceImp implements TestServiceinter { 4  5   private String name; 6  7   public String getName() { 8     return name; 9   }10 11   public void setName(String name) {12     this.name = name;13   }14 15   @Override16   public void SayHello() {17     // TODO Auto-generated method stub18     System.out.println(name+"hello");19 20   }21 22 }

MyMethodBeforeAdvice.java

 1 package com.frank.aop; 2  3 import java.lang.reflect.Method; 4  5 import org.springframework.aop.MethodBeforeAdvice; 6  7 public class MyMethodBeforeAdvice implements MethodBeforeAdvice { 8  9   @Override10   public void before(Method method, Object[] args, Object target)11       throws Throwable {12     // TODO Auto-generated method stub13     System.out.println("记录日志中。。。。"+method.getName());14 15   }16 17 }

App1.java

 1 package com.frank.aop; 2  3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPath 5  6 public class App1 { 7  8   public static void main(String[] args) { 9     // TODO Auto-generated method stub10     ApplicationContext ac=new ClassPath);11     TestServiceinter Ts=(TestServiceinter) ac.getBean("proxyFactoryBean");12     Ts.SayHello();13 14   }15 16 }

beans.

 

 1 <??> 2 <beans ="http://www.springframework.org/schema/beans" 3   ="http://www.w3.org/2001/ ="http://www.springframework.org/schema/p" 4   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> 5   <!-- 配置前置通知 --> 6   <bean id="myMethodBeforeAdvice" class="com.frank.aop.MyMethodBeforeAdvice" /> 7   <!-- 配置被代理对象 --> 8   <bean id="testServiceImp" class="com.frank.aop.TestServiceImp"> 9     <property name="name" value="frank"></property>10   </bean>11   <!-- 配置代理对象 -->12   <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">13     <!--代理接口集 -->14     <property name="proxyInterfaces">15       <list>16         <value>com.frank.aop.TestServiceinter</value>17       </list>18     </property>19     <!-- 把通知织入到代理对象 -->20     <property name="interceptorNames">21       <value>myMethodBeforeAdvice</value>22     </property>23     <!-- 配置被代理对象 -->24     <property name="target" ref="testServiceImp">25     </property>26   </bean>27 28 29 </beans>