//MyBean.java
package test.aop;
public class MyBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//MyMethodBeforeAdvice.java
package test.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println( "调用了 "+target +"的 "+method.getName()+"方法,参数为:");
int i=0;
for (Object object : args) {
System.out.println( (++i)+ "个:"+ object.toString());
}
}
}
//Test.java
package test.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:test/aop/aop.xml");
MyBean mb=(MyBean) ctx.getBean("MyBeanService");
mb.setName("abc");
mb.getName();
mb.getClass();
System.out.println("done");
}
}
////////////////////////////////////配置////////////////////////////////////////////
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="MyBean" class="test.aop.MyBean"></bean>
<bean id="MyAdvice" class="test.aop.MyMethodBeforeAdvice"></bean>
<bean id="MyBeanService" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 注入目标对象 -->
<property name="target" ref="MyBean"></property>
<!-- 注入Advice/Interceptor -->
<property name="interceptorNames">
<list>
<value>MyAdvice</value>
</list>
</property>
</bean>
</beans>