Spring入門學習(使用XML配置檔案方式來配置AOP) 第十七節
阿新 • • 發佈:2019-01-06
Spring入門學習(使用XML配置檔案方式來配置AOP)
xml配置檔案配置AOP
- 使用之前建立的類
ArithmeticCalculator
和ArithmeticCalculatorImpl
- 去掉
LoggingAspect
和ValidationAspect
類中的所有註解public class LoggingAspect { public void beforeMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature
- 建立配置檔案
applicationContext-xml.xml
如下:
在配置檔案中,使用<aop:config>
來開始配置AOP,<aop:pointcut>
配置切點表示式,<aop:aspect>
配置切面及通知。<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 配置Bean --> <bean id="calc" class="com.fafa.spring.aop.xml.ArithmeticCalculatorImpl"></bean> <!-- 配置切面的bean --> <bean id="loggingAspect" class="com.fafa.spring.aop.xml.LoggingAspect"></bean> <bean id="validationAspect" class="com.fafa.spring.aop.xml.ValidationAspect"></bean> <!-- 配置AOP --> <aop:config> <!-- 配置切點表示式 --> <aop:pointcut expression="execution(* com.fafa.spring.aop.xml.*.*(..))" id="pointCut"/> <!-- 配置切面及通知 --> <aop:aspect ref="loggingAspect" order="2"> <aop:before method="beforeMethod" pointcut-ref="pointCut" /> <aop:after method="afterMethod" pointcut-ref="pointCut"/> <aop:after-throwing method="afterThrowing" pointcut-ref="pointCut" throwing="ex"/> <aop:after-returning method="afterReturning" pointcut-ref="pointCut" returning="return"/> <!-- <aop:around method="aroundMethod" pointcut-ref="pointCut"/> --> </aop:aspect> <aop:aspect ref="validationAspect" order="1"> <aop:before method="validateArgs" pointcut-ref="pointCut"/> </aop:aspect> </aop:config> </beans>
- 測試:
測試結果:public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:applicationContext-xml.xml"); ArithmeticCalculator arithmeticCalculator = ctx.getBean(ArithmeticCalculator.class); System.out.println(arithmeticCalculator.getClass().getName()); int result = arithmeticCalculator.add(3, 6); System.out.println("result:" + result); result = arithmeticCalculator.div(6, 3); System.out.println("result:" + result); // result = arithmeticCalculator.div(6, 0); // System.out.println("result:" + result); } }
com.sun.proxy.$Proxy2 -->validate:[3, 6] The method add begins...[3, 6] The method add ends... The method add ends with 9 result:9 -->validate:[6, 3] The method div begins...[6, 3] The method div ends... The method div ends with 2 result:2