Java AOP切面编程,spring 配置文件开发方式
一,定义主要接口
package c.c.aop;
/*
* 接口类
* 主要要做的事
*
* */
public interface Sleepable {
void sleep();
}
二,继承主要接口重写类
package c.c.aop;
public class Human implements Sleepable {
/*
* 接口实现类
* 重写接口类方法
*
* */
public void sleep(){
System.out.println("睡觉了!梦中自有颜如玉!");
}
}
三,切面新添加的要执行的类
package c.c.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
/*
* 切面通知类
* */
public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{
public void before(Method mtd, Object[] arg1, Object arg2)
throws Throwable {
System.out.println("通常情况下睡觉之前要脱衣服!");
}
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
System.out.println("起床后要先穿衣服!");
}
}
四,测试的main 方法
package c.c.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAOP {
@SuppressWarnings("resource")
public static void main(String[] args){
ApplicationContext appCtx = new ClassPathXmlApplicationContext("beans-mybatis.xml");
Sleepable sleeper = (Sleepable)appCtx.getBean("humanProxy");
sleeper.sleep();
}
}
五,配置文件
<bean id="sleepHelper" class="c.c.aop.SleepHelper">
</bean>
<bean id="start" class="c.c.aop.Human">
</bean>
<bean id="sleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*sleep"/>
</bean>
<bean id="sleepHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="sleepHelper"/>
<property name="pointcut" ref="sleepPointcut"/>
</bean>
<bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="start"/>
<property name="interceptorNames" value="sleepHelperAdvisor" />
<property name="proxyInterfaces" value="c.c.aop.Sleepable" />
</bean>