戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
AOP-XML-advisor方式配置-前置通知
spring应用手册(第四部分)
springAOP的配置除过我们上面解释的aspect方式之外,还有一个非常常用的方式就是aop:advisor
aop:aspect 主要是定义一个切面(切面包含的通知和切入点);
aop:advisor 主要定义一个通知器 ,其实通知器本身也是包含了切面和切入点。
看上去没啥区别,其实底层的实现区别也不大,但是在使用上有很大的区别。
我们来看看advisor的使用方式:
业务类还是用我们之前的业务类。
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class MessageBean {
//输出信息的业务方法
public String printMessage(String msg){
System.out.println("---------业务方法------");
System.out.println("MessageBean-printMessage:"+msg);
System.out.println("---------业务方法------");
return msg;
}
}
这里不再定义切面类,而是定义一个通知类,aspect中一个通知就是一个方法,aspect类本身就是一个普通的javaBean,而在advisor中我们需要定一个通知类,通知类需要实现对应的接口,不同的通知实现不同的接口:
前置通知接口:org.springframework.aop.MethodBeforeAdvice
其中的方法:
/**
*
* @param method 目标方法对象
* @param objects 目标方法的参数列表
* @param o 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable;
我们自己顶一个BeofreAdvice:
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class DkBeforeAdvice implements MethodBeforeAdvice{
/**
*
* @param method 目标方法对象
* @param objects 目标方法的参数列表
* @param o 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("--前置通知开始--");
System.out.println("目标对象:"+o);
System.out.println("目标方法:"+method.getName());
System.out.println("参数列表:"+ Arrays.toString(objects));
System.out.println("--前置通知结束--");
}
}
业务类:
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class MessageBean {
//输出信息的业务方法
public String printMessage(String msg){
System.out.println("---------业务方法------");
System.out.println("MessageBean-printMessage:"+msg);
System.out.println("---------业务方法------");
return msg;
}
}
在业务方法中配置前置通知:
<!-- 注册Advice通知bean -->
<bean id="dBeforekAdvice" class="com.st.dk.demo9.advices.DkBeforeAdvice"/>
<!-- AOP配置 -->
<aop:config>
<!--前置通知配置-->
<!-- advice-ref指定前置通知的bean的id,pointcut配置内联的切入点,当然我们也可以使用pointcut-ref 配置声明好的切入点 -->
<aop:advisor advice-ref="dBeforekAdvice" pointcut="execution(* com.st.dk.demo9.beans..*.*(..))"/>
</aop:config>
测试:
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext-demo9.xml");
MessageBean bean = ac.getBean(MessageBean.class);
String retVal = bean.printMessage("假发的穿戴技巧");