Spring中的Advisor,Advice,Pointcut
一、Spring中的Advisor,Advice,Point概述
1、Advisor:充当Advice和Pointcut的适配器,类似使用Aspect的@Aspect注解的类(前一章节所述)。一般有advice和pointcut属性。
祖先接口为org.springframework.aop.Advisor,应用中可直接使用org.springframework.aop.support.DefaultPointcutAdvisor
2、Advice:用于定义拦截行为,祖先接口为org.aopalliance.aop.Advice,该接口只是标识接口,应用中可直接实现BeforeAdvice ,ThrowsAdvice,MethodInterceptor ,AfterReturningAdvice ,IntroductionInterceptor 等子接口
3、Pointcut:用于定义拦截目标集合,祖先接口为org.springframework.aop.Pointcut
二、Spring中的Advisor,Advice,Point的应用
1、编写Advisor实现类
在此可直接使用org.springframework.aop.support.DefaultPointcutAdvisor
2、编写Advice实现类
public class PlayAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("my before advice");
// method.invoke(target, args); 如果再调用这句,则目标方法会执行多一次
}
}
3、编写Pointcut实现类
public class PlayPointcut implements Pointcut {
public ClassFilter getClassFilter() {
return new PlayClassFilter();
}
public MethodMatcher getMethodMatcher() {
return new PlayMethodMatcher();
}
}
//PlayClassFilter的定义
class PlayClassFilter implements ClassFilter {
public boolean matches(Class clazz) {
if(clazz.getSimpleName().equals("Play"))
return true;
return false;
}
}
//PlayMethodMatcher的定义
class PlayMethodMatcher implements MethodMatcher {
public boolean isRuntime() {
return true;
}
public boolean matches(Method method, Class c) {
if(c.getSimpleName().equals("Play")&&method.getName().contains("Service"))
return true;
return false;
}
public boolean matches(Method method, Class c, Object[] args) {
if(c.getSimpleName().equals("Play")&&method.getName().contains("Service"))
return true;
return false;
}
}
4、编写目标类
public class Play {
public void playService(String what){
System.out.println("play "+what);
}
}
5、在配置文件中配置
<bean id="adviceBean" class="com.hss.sp.aop.PlayAdvice"/>
<bean id="pointcutBean" class="com.hss.sp.aop.PlayPointcut"/>
<bean id="playService" class="com.hss.sp.service.Play"/>
<bean
class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="adviceBean"></property>
<property name="pointcut" ref="pointcutBean"></property>
</bean>
6、测试,结果
BeanFactory bf=new ClassPathXmlApplicationContext("applicationContext.xml");
Play play=(Play)bf.getBean("playService");
play.playService("pingpong");
输出:
my before advice
play pingpong