1.作用:外部文件提取本部文件的参构造函数的返回值(即提取返回值,这也是它叫returning的原因),并可以在主语句输出后,外部添加进一两句语句(即添加一两个功能)
2.@AfterReturning的属性值,pointcut/value和returning.
pointcut/value:其实pointcut和value这两宝贝作用是一样的,只不过pointcut设定之后value会被覆盖掉(即pointcut>value)
returning : 指定一个返回值形参名
3.代码说明真相
3.1.主类文件(主调bean)
package test;import org.sPRingframework.stereotype.Component;@Componentpublic class component { public String test(String name) { System.out.println(name+"吃西瓜"); return name; }}
3.2.定义一个切面类为主类服务
package test;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Aspect; //定义了一个切面(切面的意思是:业务流程运行的某个特定步骤,也就是应用运行过程的关注点 ,关注点可能横切多个对象,所以也常常被称为横切关注点)@Aspect public class aspect { @AfterReturning(pointcut="execution(* test.*.*(..))",returning="name") public void log(Object name) { System.out.println("获取目标方法返回值:"+name); System.out.println("模拟记录日志功能"); }}
3.3配置文件
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd "> <context:component-scan base-package="test"> <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>//重要类,起一个拦截效果,将符合条件的java类会被拦截,并当做一个bean类处理 </context:component-scan> <aop:aspectj-autoproxy/></beans>
3.4运行类
package test;import org.springframework.context.applicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class function { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml"); component com=ac.getBean(component.class); com.test("傻瓜"); }}3.5输出结果
4.总结:
@AfterReturning取得主类带参构造返回值的过程
1.主类带参构造方法调用了return,该return后面的值正是@AfterReturning索取的值,上面例子中为"傻瓜"--->2.return值通过切面类的@AfterReturning的<context type中的拦截器>将值赋值给了切面类的name值,---->3.@AfterReturning中的name赋值给了切面类中的构造带参方法----->5.在该方法中输出了该值.
新闻热点
疑难解答