最近学习Spring,一直不太明白Srping的切面编程中的的argNames的含义,经过学习研究后,终于明白,分享一下
需要监控的类:
package bean; public class HelloApi { public void aspectTest(String a,String b){ System.out.println("in aspectTest:" + "a:" + a + ",b:" + b); } }
类HelloApi的aspectTest方法是需监控的方法,目标是调用前获取获得入参a和b的值,并打印出来。
切面类:
package aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import java.lang.String; @Component @Aspect public class HelloApiAspect2 { @Pointcut(value="execution(* bean.HelloApi.aspectTest(..)) && args(a1,b2)",argNames="a1,b2") public void pointcut1(String a1,String b2){} @Before(value="pointcut1(a,b)",argNames="a,b") public void beforecase1(String a,String b){ System.out.println("1 a:" + a +" b:" + b); } //注意和beforecase1的区别是argNames的顺序交换了 @Before(value="pointcut1(a,b)",argNames="b,a") public void beforecase2(String a,String b){ System.out.println("2 a:" + a +" b:" + b); } }
测试类:
package UnitTest; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import bean.HelloApi; public class Test1 { @Test public void aspectjTest1(){ BeanFactory beanFactory = new ClassPathXmlApplicationContext("chapter2/aspectTest1.xml"); HelloApi helloapi1 = beanFactory.getBean("helloapi1",HelloApi.class); helloapi1.aspectTest("a", "b"); } }
Spring的配置文件aspectTest.xml:
<?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:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http:<div style="color:transparent">本文来源gaodai.ma#com搞#代!码(网</div>//www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="aspect"></context:component-scan> <bean id="helloapi1" class="bean.HelloApi"></bean> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
输出:
2 a:b b:a
1 a:a b:b
in aspectTest:a:a,b:b
说明:
HelloApiAspect2定义了一个切面pointcut,切面表达式是execution(* bean.HelloApi.aspectTest(..)) && args(a1,b2),表示配对bean.HelloApi.aspectTest()方法,并且传入参数是2个。
args(a1,b2)另外一个作用,就是定义了aspectTest(String a,String b)方法对应表达式args(a1,b2)。定义了args(a1,b2),才能把目标方法aspectTest的参数传入到切面方法beforecase1的参数中,a参数对应a1,b参数对应b2。使用的方法是按顺序一一对应,aspectTest第一个参数对args第一个参数,aspectTest第2个参数对args第2个参数.