接口类
package cn.com.gan.spring.aop;
public interface IHello {
public void SayHello();
public void sayHelloAgain();
}
实现类
package cn.com.gan.spring.aop;
public class ImpHello implements IHello {
@Override
public void SayHello() {
System.out.println("hello everybody!");
}
@Override
public void sayHelloAgain(){
System.out.println("hello everybody again");
}
}
advice类(aspect)
package cn.com.gan.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class LoggerBefore implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("我在方法前插入日志");
}
}
package cn.com.gan.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class LoggerAfter implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println("打完招呼了!");
}
}
package cn.com.gan.spring.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class loggerAdvisor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation object) throws Throwable {
Object o=null;
try{
System.out.println("记录日志");
}finally{
o=object.proceed();
System.out.println("记录完毕");
}
return o;
}
}
操作类
package cn.com.gan.spring.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringManager {
public static void main(String[] args){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationAopContext.xml");
IHello hello=(IHello)ac.getBean("proxyhello");
hello.SayHello();
hello.sayHelloAgain();
}
}
配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ">
<bean id="hello" class="cn.com.gan.spring.aop.ImpHello"></bean>
<bean id="loggera" class="cn.com.gan.spring.aop.LoggerAfter"></bean>
<bean id="loggerb" class="cn.com.gan.spring.aop.LoggerBefore"></bean>
<bean id="logger" class="cn.com.gan.spring.aop.loggerAdvisor"></bean>
<bean id="proxyhello" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>cn.com.gan.spring.aop.IHello</value>
</property>
<property name="target">
<ref local="hello" />
</property>
<property name="interceptorNames">
<list>
<value>loggerb</value>
<value>loggera</value>
<value>logger</value>
</list>
</property>
</bean>
</beans>
advice执行顺序 先执行loggerb中方法 ,然后执行logger 最后执行loggera。
这种方式的话在IHello接口中定义的所有方法都会被执行advice。如果限定那些方法要执行的话就要用到advisor(pointcut)。