spring-aop代码示例

spring-aop代码示例
【README】增强器-Advisor Pointcut Advice增强点 Pointcut 切点在哪里增强增强方法 Advice 增强逻辑拦截器MethodInterceptor运行时执行增强逻辑的统一拦截接口组成责任链调用多个拦截器解析切面逻辑的组装步骤Before/After/AroundAdvice 增强逻辑AdvisorAdvice Pointcut;AdvisorAdapterRegistryMethodInterceptorReflectiveMethodInvocationProceed()目标方法【1】spring aspectJ 增强【业务bean】Slf4j public class TomAddrBean { private String addr ChengDu; public void test() { log.info(addr {}, addr); } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr addr; } }【切面类】Aspect Slf4j public class TomAddrAspect { Pointcut(execution(* *.test(..))) public void test() { // do nothing. } Before(test()) public void beforeTest() { log.info(before test()); } After(test()) public void afterTest() { log.info(after test()); } Around(test()) public Object aroundTest(ProceedingJoinPoint proceedingJoinPoint) { log.info(around: before test()); Object result null; try { result proceedingJoinPoint.proceed(); } catch (Throwable e) { log.error(test() 目标方法调用异常, e); throw new RuntimeException(test() 目标方法调用异常); } log.info(around: after test()); return result; } }【 beans0701_aspect.xml 】?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:aophttp://www.springframework.org/schema/aop xmlns:contexthttp://www.springframework.org/schema/context xsi:schemaLocation http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/aop/spring-context-3.0.xsd aop:aspectj-autoproxy / !-- BeanFactory PostProcessor -- bean classcom.tom.srccode.deep.analysis.chapter0501.aop.aspect.TomAddrBean / bean classcom.tom.srccode.deep.analysis.chapter0501.aop.aspect.TomAddrAspect/ /beans【测试main】public class TomAddrAspectMain { public static void main(String[] args) { ApplicationContext applicationContext new ClassPathXmlApplicationContext(/a_src_deep_analysis/chapter05/beans0701_aspect.xml); // 调用目标方法 applicationContext.getBean(TomAddrBean.class).test(); } }【运行结果】- around: before test() - before test() - addr ChengDu - after test() - around: after test()