面向切面(AOP)

使用面向切面(AOP)对现用程序插入日志大致分为两种形式:

1、通过配置文件对切入点进行操作。

2、通过注解方式对切入点进行操作。

一:准备工作。需要的jar包:(可直接放入pom文件的<dependencies>标签中,版本号如果和项目中使用的spring等版本不对应自可行更改,jar包文件稍后补充,也可自行百度)

      <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.9</version>
        </dependency>

二:通过配置文件对切入点进行操作

1、创建被切入的类

package com.joe.aop.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.boco.rnop.vr.service.IvrIndoorService;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

@Controller
@RequestMapping("/checkIndoor")
public class vrIndoor {
	@Resource
	IvrIndoorService service;
	
	@ResponseBody
	@RequestMapping(value="{buildingID}", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
	public void getName(@RequestParam String buildingID,HttpServletRequest request, HttpServletResponse response){
		
		JSONObject resultJson = new JSONObject();
		try {
			 response.setCharacterEncoding("UTF-8");
			 response.setContentType( "application/json;charset=utf-8");
			//根据html指定的jsonp回调的参数名,获取回调函数的名称
			String callbackName = request.getParameter("callback");
			System.out.println("输入的buildingID为"+buildingID);
			
			resultJson = new JSONObject();
			if("".equals(callbackName) || null==callbackName){
				response.getWriter().write(resultJson.toString());
			}else {
				response.getWriter().write(callbackName + "([" + resultJson + "])");
			}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2、编写插入的类

package com.joe.aop.controller;

public class aop {

	public void aoptest(){
		System.out.println("*************************aoptest*************************");
	}
}

3、修改配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
	<!-- 自动扫描 -->
	<context:component-scan base-package="com.joe.aop.controller" />
        <!-- 配置文件依赖注入的方式进行aop切入日志 -->
	
	<bean id="aop" class="com.joe.aop.controller.aop"></bean>
	 <aop:aspectj-autoproxy />
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
        <aop:config proxy-target-class="true">
        <aop:aspect ref="aop">
            <aop:pointcut expression="execution(* com.joe.aop.controller.vrIndoor.getName(..))"
                id="register" />
            <aop:before method="aoptest" pointcut-ref="register" />
        </aop:aspect>
    </aop:config> 

【注:】配置文件中标记红色的部分必须添加,否则程序运行会提示“通配符的匹配很全面,但无法找到元素 'aop:aspectj-autoproxy' 的声明”等错误。

4、测试:启动服务器输入请求url,控制台在打印出vrindoor输出的结果前,会将aoptest中的数据先输出。

当然,如果不通过这种方式,直接测试也可以:

将vrIndoor去掉所有的注解写成普通的类,然后写一个含有main方法类,main方法中读取配置文件(此时需要先在配置文件中创建vrIndoor的bean——><id="vr" class="com.joe.aop.controller.vrIndoor">)

ApplicationContext appCtx = new
	 ClassPathXmlApplicationContext("applictionContext.xml");
vrIndoor a = (vrIndoor)appCtx.getBean("vr");
a.getName(三个参数值)

在控制台也会输出预期的结果。

三:通过注解方式对切入点进行操作

1、修改配置文件,只需要保留 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>这一个就可以

2、需要被插入的类

package com.joe.aop.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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;

@Aspect
@Component
public class NoeAop {

	
	//直接对切入的方法进行操作,无法获取切入点的信息
	 @Before("execution(* com.joe.aop.controller.vrIndoor.getName(..))")  
	    public void deleteBigMeeting_Before(JoinPoint joinPoint){  
	        System.out.println("这里是目标方法执行前先执行");  
	    }  
	    @AfterReturning(returning = "entity",value = "execution(* com.joe.aop.vrIndoor.getName(..))")  
	    public void deleteBigMeeting_After(JoinPoint joinPoint,Object entity){  
	        System.out.println("这里是目标方法执行完并成功返回结果 正常结束后才执行");  
	        System.out.println("方法的返回结果为"+entity);  
	        System.out.println("目标方法内的参数为"+ Arrays.asList(joinPoint.getArgs()));
	        
	        List<Object> list = Arrays.asList(joinPoint.getArgs());
	        
	        for(int index=0;index<list.size();index++){
	        	System.out.println(list.get(index).getClass());
	        }
	    }  
	    @AfterThrowing(throwing = "e",value = "execution(* com.joe.aop.controller.vrIndoor.getName(..))")  
	    public void deleteBigMeeting_Throw(Throwable  e){  
	        System.out.println("这里是目标方法抛出异常后才执行");  
	        System.out.println("异常信息为"+e);  
	    }
	
	//获得切入点的信息
	//由于vrIndoor中只有一个方法,所以使用vrIndoor.*对所有方法操作,此处也可以也称vrIndoor.getName
        @Pointcut("execution(public void com.joe.aop.controller.vrIndoor.*(..))")
	public void getHttpServletMSG(){}
        //【注:下一行args()中的参数名,必须和vrIndoor方法中(这个demo中是和getName的参数名一模一样)的参数名一模一样】
	@Before("getHttpServletMSG() && args(buildingID,request,response)")
	public void before(String buildingID,HttpServletRequest request, HttpServletResponse response){
		System.out.println("*****************************before客户端信息*************************************");
		System.out.println("准备获取切入点的信息:"+buildingID);
		System.out.println("IP:"+request.getParameter("x-forwarded-for"));
		System.out.println("*****************************before客户端信息*************************************");
	}
	
	@After("getHttpServletMSG() && args(buildingID,request,response)")
	public void after(String buildingID,HttpServletRequest request, HttpServletResponse response){

		System.out.println("*****************************after客户端信息*************************************");
		System.out.println("准备获取切入点的信息:"+buildingID);
		System.out.println("*****************************after客户端信息*************************************");
	}
}

然后启动服务访问url即可。当然这个也可以进行和 二.4一样的操作

SpringAOP的切点表达式详解点击打开链接

SpringAOP注解(@Before,@After等等)详解点击打开链接


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值