spingAop——小白入门运用例子

来源:互联网 发布:mac系统字体库 编辑:程序博客网 时间:2024/05/18 18:01

测试环境:
spring4.1

aop相关jar包:
aopalliance.jar
aspectjrt-1.8.11
aspectjtools-1.8.13
aspectjweaver-1.8.10

  1. 在springmvc的配置文件中开启注解(注意:在sqring配置文件中开启注解可能使aop无效)

          <!-- 启用aop切面注解 -->

 <aop:aspectj-autoproxy proxy-target-class="true" />


     2.编写测试类:

package com.test;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;/*** @author TGY:* @version 1.0* createtime:2017年12月16日 下午3:48:45* 类说明:*/@Controller@RequestMapping("testaop")public class Test_AOP {@RequestMapping("/get")@ResponseBodypublic String test_aop(){System.out.println("测试方法功能~");return "访问完成";}}


3.编写切面类:

package com.test;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;/*** @author TGY:* @version 1.0* createtime:2017年12月16日 下午3:52:06* 类说明:*/@Aspect@Componentpublic class Deal_Aop {@Pointcut("execution(* com.test.Test_AOP.test_aop(..))")//第一个*号后面有个空格 ,不然会报:java.lang.IllegalArgumentException//execution:在方法执行时触发  //*:返回任意类型  //concert.Performance:方法所属类  //perform:方法名  //(..):使用任意参数public void Pointcut(){}//这时的Pointcut()即代表一个切面@Before("Pointcut()")public void before(){System.out.println("访问方法之前------------------");}@After("Pointcut()")public void after(){System.out.println("访问方法之后+++++++++++++++++");}}


4.进行结果:

进行项目访问:http://localhost:8080/project/testaop/get

控制台结果:


原创粉丝点击