1.在Spring入门实例的基础上添加一个拦截器(Spring的AOP也需要实现特定的接口。Spring把这些实现了特定AOP接口的类称为拦截器):
package com.spring.impl;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.aop.MethodBeforeAdvice;
public class MethodBeforeAdviceImpl implements MethodBeforeAdvice
{
@Override
public void before(Method method, Object[] args, Object obj)
throws Throwable {
System.out.println("运行前检查......");
System.out.println("method:"+method.getName());
System.out.println("Args:"+Arrays.asList(args));
System.out.println("Objects:"+obj);
}
}
2.修改配置文件applicationContext.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: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="methodBeforeAdviceImpl" class="com.spring.impl.MethodBeforeAdviceImpl"></bean>
<bean id="theAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<ref local="methodBeforeAdviceImpl"/>
</property>
<property name="mappedName" value="*"></property><!-- 拦截所有的方法 -->
</bean>
<bean id="daoImpl" class="com.spring.impl.DaoImpl"></bean>
<bean id="serviceImpl" class="com.spring.service.ServiceImpl">
<property name="idao" ref="daoImpl"></property>
</bean>
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames" value="theAdvisor"></property>
<property name="target">
<ref local="serviceImpl"/>
</property>
</bean>
</beans>
3.测试类中将获取的bean改为代理类的id:
package com.spring.junit;
import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.spring.inter.IService;
public class test1
{
@Test
public void test()
{
XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource("applicationContext.xml"));
IService hello =(IService) factory.getBean("proxy");
hello.service("HelloBean");
factory.destroySingletons();
}
}
运行结果为:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
运行前检查......
method:service
Args:[HelloBean]
Objects:com.spring.service.ServiceImpl@1968e23
早上好,HelloBean