日期:2014-05-19 浏览次数:20679 次
package study.spring.aop.account;
import java.util.List;
public interface IAccount {
public List<String> getAllAccount();
public String getAccountById(String id);
}
package study.spring.aop.account.impl;
import java.util.List;
import study.spring.aop.account.IAccount;
public class AccountImpl implements IAccount {
public List<String> getAllAccount() {
// TODO Auto-generated method stub
return null;
}
public String getAccountById(String id) {
// TODO Auto-generated method stub
return null;
}
}
package study.spring.aop.advice;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeMethodAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("方法调用之前...");
System.out.println("下面是方法调用的信息:");
System.out.println("所执行的方法是:" + method);
System.out.println("调用方法的参数是:" + args);
System.out.println("目标对象是:" + target);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-autowire="byName" default-lazy-init="true">
<bean id="account" class="study.spring.aop.account.impl.AccountImpl" />
<!-- 第一个拦截器-->
<bean id="myBeforeAdvice" class="study.spring.aop.advice.MyBeforeMethodAdvice"/>
<!-- 使用ProxyFactoryBean 产生代理对象-->
<bean id="accountProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 设置目标对象 -->
<property name="target">
<ref bean="account" />
</property>
<!-- 这里是代理的接口 -->
<property name="proxyInterfaces">
<list>
<value>study.spring.aop.account.IAccount</value>
</list>
</property>
<!-- 代理对象所使用的拦截器-->
<property name="interceptorNames">
<list>
<value>myBeforeAdvice</value>
</list>
</property>
</bean>
</beans>
package study.spring.aop;
import org.springframework.test.AbstractSingleSpringContextTests;
import study.spring.aop.account.IAccount;
public class SpringTest extends AbstractSingleSpringContextTests {
@Override
protected String[] getConfigLocations() {
return new String[] { "classpath:applicationContext.xml" };
}
public void testApp() {
IAccount account = (IAccount) this.getApplicationContext().getBean("account");
account.getAccountBy