和前文一样,aop示例也拿helloworld演示。
IHelloService 接口:
public interface IHelloService {
public void sayHello();
}
HelloServiceImpl 实现类
public class HelloServiceImpl implements IHelloService{
@Override
public void sayHello(){
System.out.println("Hello!");
}
}
IHelloAction 接口
public interface IHelloAction {
/*
* 方便JUnit测试,增加返回值
*/
public boolean sayHello();
}
HelloActionImpl 实现类
public class HelloActionImpl implements IHelloAction{
private IHelloService helloService;
public boolean sayHello(){
/*
* 增加try-catch用于JUnit测试
*/
boolean flag = true;
try {
helloService.sayHello();
} catch (RuntimeException e) {
e.printStackTrace();
flag = false ;
}
return flag;
}
public void setHelloService(IHelloService helloService) {
this.helloService = helloService;
}
}
spring配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="helloService" class="cn.com.ultrapower.service.HelloServiceImpl">
</bean>
<bean id="helloActionTarget" class="cn.com.ultrapower.action.HelloActionImpl">
<property name="helloService"><ref bean="helloService"/></property>
</bean>
<!--设置一个日志监听器-->
<bean id="logAdvisorBefore" class="cn.com.ultrapower.advice.ordinary.LogAdvisorBefore" />
<!--利用aop实现日志监听支持-->
<bean id="helloAction" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"><value>cn.com.ultrapower.action.IHelloAction</value></property>
<!--被代理对象-->
<property name="target"><ref local="helloActionTarget"/></property>
<!--拦截器-->
<property name="interceptorNames">
<list>
<value>logAdvisorBefore</value>
</list>
</property>
</bean>
</beans>
logAdvisorBefore 是用于在方法执行前监听,helloAction并不直接指向HelloActionImpl类,而是通过ProxyFactoryBean创建。helloActiond的target属性引用了helloActionTarget bean,并且增加了proxyInterfaces和interceptorNames两个属性。前者指向IHelloAction接口,后者是一list,也就意味着可以增加多个拦截器。如果使用过spring的事务,对上面代码的方式应该很熟悉。
logAdvisorBefore 代码如下:
public class LogAdvisorBefore implements MethodBeforeAdvice {
/**
* method - method being invoked
* args - arguments to the method
* target - target of the method invocation. May be null.
*/
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("Log:do something before call");
System.out.println("Log:call method name:"+method.getName());
}
}
从实现的是MethodBeforeAdvice 接口的字面意思上就可以看出,这个是一个在方法执行前的监听器(这里是用监听不使用拦截是因为拦截有阻止执行的功能,而MethodBeforeAdvice 没有这个功能)
使用junit测试上面代码,输出如下:
Log:do something before call
Log:call method name:sayHello
Hello!
可见,LogAdvisorBefore 中的before方法是在action.sayHello()方法之前执行。