Spring AOP的配置

来源:互联网 发布:知轩藏书 编辑:程序博客网 时间:2024/05/18 19:44

Beans.xml:


<?xml version="1.0" encoding="utf-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 配置被代理对象 --><bean id="testService" class="com.dqd.aop.TestService"><property name="name" value="dqd"></property></bean>  <!-- 配置前置通知 --><bean id="myMethodBeforeAdvice" class="com.dqd.aop.MyMethodBeforeAdvice" />   <!-- 配置代理对象 --> <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean"> <!-- 代理接口集 --> <property name="proxyInterfaces"> <list> <value>com.dqd.aop.TestInter</value> <value>com.dqd.aop.TestInter2</value> </list> </property> <!-- 把通知织入代理对象 --> <property name="interceptorNames"> <!-- 相当于把前置通知和代理对象关联起来,也可理解为拦截器 --> <value>myMethodBeforeAdvice</value> </property> <!-- 配置被代理对象,可以指定 --> <property name="target" ref="testService" /><!-- 指向代理对象 --> </bean> </beans>

一个实现两个接口的类:


package com.dqd.aop;public class TestService implements TestInter,TestInter2{private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}public void sayHello(){System.out.println("hi !"+name);}public void sayBey(){System.out.println("Bye !"+name);}}


通知的配置:


package com.dqd.aop;import java.lang.reflect.Method;import org.springframework.aop.MethodBeforeAdvice;public class MyMethodBeforeAdvice implements MethodBeforeAdvice {@Overridepublic void before(Method method, Object[] args, Object target)throws Throwable {// TODO Auto-generated method stubSystem.out.println("记录日志:"+method.getName());}}


Test:


package com.dqd.aop;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class app1 {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("com/dqd/aop/Beans.xml");TestInter ts = (TestInter) ac.getBean("proxyFactoryBean");//注意ac中含有接口1和2但是我们使用的接口1来接受的,但是可以强转为接口2的类型ts.sayHello();((TestInter2)ts).sayBey();}}















0 0
原创粉丝点击