Spring AOP是一个非常好的东西,AOP也就是面向切面编程。主要实现方式有三种,在这里我们以代理的方式实现。我们以一个人睡觉为例子讲解,使用的开发工具是Myeclipse。
1.首先我们需要创建一个接口,Sleepable,所有的人都可以睡觉。
package Spring_AOP_init;
public interface Sleepable {
void sleep();
}
2.新建一个Human类来实现这个接口,人类可以睡觉
package Spring_AOP_init_impl;
import Spring_AOP_init.Sleepable;
public class Human implements Sleepable{
public void sleep() {
// TODO Auto-generated method stub
System.out.println("Go to sleep,Get a good dream!");
}
}
3.但是一个人睡觉的时候不光光只是睡觉,他还要做一些其他的动作,比如说睡觉之前要脱衣服,起来的时候要穿衣服,所以除了睡觉这个业务逻辑以外,我们需要添加些额外的功能,MethodBeforeAdvice,AfterReturningAdvice这两个接口可以就是增强接口,前置和后置。
package Spring_AOP_init_impl;
import java.lang.reflect.Method;
import org.springframework.aop.*;
public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("We need dress out before sleep!");
}
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
// TODO Auto-generated method stub
System.out.println("We need dress in cloth after sleep!");
}
}
4.之后就是最重要的配置配置文件了
<?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="human" class="Spring_AOP_init_impl.Human"></bean>
<!-- 定义通知内容,就是切入点执行前后需要做的业务 -->
<bean id="sleephelper" class="Spring_AOP_init_impl.SleepHelper"></bean>
<!-- 定义切入点位置 -->
<bean id="sleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*sleep"></property>
</bean>
<!-- 使切点与通知关联起来,完成切面的设置 -->
<bean id="sleephelperadvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="sleephelper"></property>
<property name="pointcut" ref="sleepPointcut"></property>
</bean>
<!-- 设置代理 -->
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理的对象 -->
<property name="target" ref="human"></property>
<!-- 使用切面 -->
<property name="interceptorNames" value="sleephelperadvisor"></property>
<!-- 代理接口,代替睡觉 -->
<property name="proxyInterfaces" value="Spring_AOP_init.Sleepable"></property>
</bean>
</beans>
5.配置完成以后也就将这个代理的过程弄好了,之后就是测试了,新建一个测试类。
package org.etspace.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import Spring_AOP_init.Sleepable;
public class Test_AOP_Proxy {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new FileSystemXmlApplicationContext("src/applicationContext.xml");
Sleepable human=(Sleepable)ac.getBean("proxy");
human.sleep();
}
}
进行测试
这就是代理实现AOP的全部过程啦,还有其他的两种方式正在学习中~