spring:註解配置AOP

註解配置AOP(使用 AspectJ 類庫實現的),大體分爲三步: 
1. 使用註解@Aspect來定義一個切面,在切面中定義切入點(@Pointcut),通知類型(@Before, @AfterReturning,@After,@AfterThrowing,@Around). 
2. 開發須要被攔截的類。 
3. 將切面配置到xml中,固然,咱們也能夠使用自動掃描Bean的方式。這樣的話,那就交由Spring AoP容器管理。 java

另外須要引用 aspectJ 的 jar 包: aspectjweaver.jar aspectjrt.jar web

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------spring

pom中的jar包支持數據庫

<!--spring-aop依賴 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
-----------------------------------------------------------------------------------------------------------------
自定義註解Controller部分
package cn.cjq.util.aop;

import java.lang.annotation.*;

/**
*自定義註解 攔截Controller
*/

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemControllerLog {
String description() default "";
}
---------------------------------------------------------------------------------------------------------------
自定義註解Service業務部分
package cn.cjq.util.aop;
import java.lang.annotation.*;
/**
*自定義註解 攔截service
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
String description() default "";
}
--------------------------------------------------------------------------------------------------------------------------------
切面類
package cn.cjq.util.aop;

import cn.cjq.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
* 切點類
* @author cjq
* @since 2017-11-28
* @version 1.0
*/
@Aspect
@Component
public class SystemLogAspect {

//本地異常日誌記錄對象
private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class);

//Service層切點
@Pointcut("@annotation(cn.cjq.util.aop.SystemServiceLog)")
public void serviceAspect() {
}

//Controller層切點
@Pointcut("@annotation(cn.cjq.util.aop.SystemControllerLog)")
public void controllerAspect() {
}

/**
* 前置通知 用於攔截Controller層記錄用戶的操做
*
* @param joinPoint 切點
*/
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) {

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
//讀取session中的用戶
User user = (User) session.getAttribute("user");
//請求的IP
String ip = request.getRemoteAddr();
try {
//*========控制檯輸出=========*//
System.out.println("=====前置通知開始=====");
System.out.println("請求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
//System.out.println("請求人:" + user.getUsername());
System.out.println("請求IP:" + ip);
//*========數據庫日誌=========*//
/*Log log = SpringContextHolder.getBean("logxx");
log.setDescription(getControllerMethodDescription(joinPoint));
log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
log.setType("0");
log.setRequestIp(ip);
log.setExceptionCode( null);
log.setExceptionDetail( null);
log.setParams( null);
log.setCreateBy(user);
log.setCreateDate(DateUtil.getCurrentDate());
//保存數據庫
logService.add(log);*/
System.out.println("=====前置通知結束=====");
} catch (Exception e) {
System.out.println("=====Controller通知結束=====");
//記錄本地異常日誌
logger.error("==前置通知異常==");
logger.error("異常信息:{}", e.getMessage());
}
}

/**
* 異常通知 用於攔截service層記錄異常日誌
*
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
//讀取session中的用戶
User user = (User) session.getAttribute("user");
//獲取請求ip
String ip = request.getRemoteAddr();
//獲取用戶請求方法的參數並序列化爲JSON格式字符串
String params = "";
if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
for ( int i = 0; i < joinPoint.getArgs().length; i++) {
params += joinPoint.getArgs()[i] + ";";
}
}
try {
/*========控制檯輸出=========*/
System.out.println("=====異常通知開始=====");
System.out.println("異常代碼:" + e.getClass().getName());
System.out.println("異常信息:" + e.getMessage());
System.out.println("異常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
//System.out.println("請求人:" + user.getUsername());
System.out.println("請求IP:" + ip);
System.out.println("請求參數:" + params);
/*==========數據庫日誌=========*/
/*Log log = SpringContextHolder.getBean("logxx");
log.setDescription(getServiceMthodDescription(joinPoint));
log.setExceptionCode(e.getClass().getName());
log.setType("1");
log.setExceptionDetail(e.getMessage());
log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
log.setParams(params);
log.setCreateBy(user);
log.setCreateDate(DateUtil.getCurrentDate());
log.setRequestIp(ip);
//保存數據庫
logService.add(log);*/
System.out.println("=====異常通知結束=====");
} catch (Exception ex) {
System.out.println("=====Service通知結束=====");
//記錄本地異常日誌
logger.error("==異常通知異常==");
logger.error("異常信息:{}", ex.getMessage());
}
/*==========記錄本地異常日誌==========*/
logger.error("異常方法:{}異常代碼:{}異常信息:{}參數:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);

}


/**
* 獲取註解中對方法的描述信息 用於service層註解
*
* @param joinPoint 切點
* @return 方法描述
* @throws Exception
*/
public static String getServiceMthodDescription(JoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SystemServiceLog. class).description();
break;
}
}
}
return description;
}

/**
* 獲取註解中對方法的描述信息 用於Controller層註解
*@SystemControllerLog(description = "用戶登陸") 該方法獲取描述部分
    * @param joinPoint 切點
* @return 方法描述
* @throws Exception
*/
public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
String description = "";
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description = method.getAnnotation(SystemControllerLog. class).description();
break;
}
}
}
return description;
}
}
----------------------------------------------------------------------------------------------------------------------------------------
xml配置支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
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-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--劃紅線的爲配置aop必須的xml文件頭 -->

<aop:aspectj-autoproxy/> <!--這行對aop配置相當重要,且必須放在spring-mvc配置文件中方可生效 -->
<!-- 自動掃描(自動注入) -->
<context:component-scan base-package="cn.cjq.controller;cn.cjq.api;"/>
<mvc:annotation-driven  /><!-- cache-period="315360000" -->
--------------------------------------------------------------------------------------------------------
實例:Controller前置攔截
/**
* 用戶登陸
*/
@ResponseBody()
@RequestMapping(value = "userLogin")
@SystemControllerLog(description = "用戶登陸")
public Object userLogin(
@RequestParam(value="userName",required=false,defaultValue="") String userName,
@RequestParam(value="passWord",required=false,defaultValue="") String passWord,
@RequestParam(value="rememberMe",required=false,defaultValue="0") boolean rememberMe,
@RequestParam(value="validateCode",required=false,defaultValue="") String validateCode,
@RequestParam(value="userType",required=false,defaultValue="") String userType
) throws Exception{
String error=null;
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord,rememberMe);
try {
subject.login(token);
//如何可以訪問到已經在 Realm 中獲取到的 User 的實例.
//Object principal = SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

} catch (UnknownAccountException e) {
error = "用戶名/密碼錯誤";
} catch (IncorrectCredentialsException e) {
error = "用戶名/密碼錯誤";
} catch (AuthenticationException e) {
//其餘錯誤,好比鎖定,若是想單獨處理請單獨catch處理
error = "其餘錯誤:" + e.getMessage();
}
Map<Object, Object> result = new HashMap<Object, Object>();
if(error != null ){
result.put("success", false);
result.put("message", error);
}else{
User user = userServiceImpl.findByUserName(userName);
Session sessions = subject.getSession();
sessions.setAttribute("user",user );
result.put("success", true);
}
return result;
}
實例2:service異常攔截
/**
* 根據用戶名查詢帳號信息
*/
@SystemServiceLog(description = "查詢帳號信息異常")public User findByUserName (String username)throws Exception{ User user = new User(); List<User> accList = userMapper.findByUserName(username); if(accList.size()>0){ user = accList.get(0); }else{ user = null; } return user;}
相關文章
相關標籤/搜索