<?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="test1Service" class="com.hsp.aop.Test1Service">
<property name="name" value="小明"></property>
</bean>
<!-- 配置前置通知 -->
<bean id="MyMethodBeforeAdvice" class="com.hsp.aop.MyMethodBeforeAdvice"></bean>
<!-- 配置代理对象 -->
<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理接口集 -->
<property name="proxyInterfaces">
<list>
<value>com.hsp.aop.TestServiceInter</value>
<value>com.hsp.aop.TestServiceInter2</value>
</list>
</property>
<!-- 把 通知 织入到代理对象 -->
<property name="interceptorNames">
<!-- 相当于把MyMethodBeforeAdvice前置通知和代理对象关联,我们可以把通知看成拦截器 -->
<value>MyMethodBeforeAdvice</value>
</property>
<!-- 可以指定被代理的对象 -->
<property name="target" ref="test1Service">
</property>
</bean>
</beans>
以上是xml的配置文件
package com.hsp.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
/**
*
* method:被调用的方法
* args:方法参数
* target:调用目标
*/
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("日志写啦"+method.getName());
System.out.println(target);
}
}
package com.hsp.aop;
public interface TestServiceInter {
public void sayHello();
}
package com.hsp.aop;
public interface TestServiceInter2 {
public void sayBye();
}
package com.hsp.aop;
public class Test1Service implements TestServiceInter,TestServiceInter2 {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("hello"+name);
}
@Override
public void sayBye() {
// TODO Auto-generated method stub
System.out.println("bye"+name);
}
}
package com.hsp.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/aop/beans.xml");
TestServiceInter tsi=(TestServiceInter) ac.getBean("proxyFactoryBean");
tsi.sayHello();
((TestServiceInter2)tsi).sayBye();
}
}