aop使用,在sql查詢後統一解密AES密碼
阿新 • • 發佈:2018-11-08
第一步,引入jar。
第二步,在spring的類載入掃描配置檔案中加入
<aop:config proxy-target-class="true"/>
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.audaque.**.aop" />
第三步,編寫自己的處理類
package com.audaque.module.datasource.aop; import com.audaque.module.datasource.model.DataSource; import com.audaque.module.datasource.utils.AESUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @param null * @Description: 資料來源密碼處理 * @Author: LGH * @CreateDate: 2018/10/18 11:31 */ @Aspect @Component public class PasswordFieldHandler { /* @Before("execution(* com.audaque.module.datasource.mapper..*.add*(..))") public void add_Before(JoinPoint joinPoint){ Object[] objArr = joinPoint.getArgs(); for (Object object : objArr) { invokeEnum(object,"getValueByLable"); } } @Before("execution(* com.audaque.module.datasource.mapper..*.insert*(..))") public void insert_Before(JoinPoint joinPoint){ Object[] objArr = joinPoint.getArgs(); for (Object object : objArr) { invokeEnum(object,"getValueByLable"); } }*/ @AfterReturning(returning = "entity",value = "execution(* com.audaque.module.datasource.mapper.DataSourceMapper.findBy*(..))") public void get_After(JoinPoint joinPoint,Object entity) throws IllegalAccessException, IntrospectionException, InvocationTargetException { invokeEnum(entity); } private void invokeEnum(Object entity) throws IntrospectionException, InvocationTargetException, IllegalAccessException { String id = "0"; System.out.println("這裡是目標方法執行前先執行22"); Class clazz = entity.getClass(); DataSource dataSource=(DataSource)entity; //獲取主鍵值 Field[] fields = entity.getClass().getDeclaredFields(); for (Field field : fields) { if("password".equals(field.getName())){ System.out.println(field.getName()); PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass()); Method getMethod = pd.getReadMethod(); Object o1 = getMethod.invoke(entity); System.out.println("解壓前"+o1.toString()); String password=AESUtils.invokeDecryptEncode(o1.toString()); System.out.println("解壓後"+password); dataSource.setPassword(password); // field.set(entity, password); break; } } entity=dataSource; } }
這裡做了密碼的解密,因為是多資料來源管理,很多地方呼叫,密碼都需要解密,故在這裡統一解密,
com.audaque.module.datasource.mapper.DataSourceMapper.findBy 指定此類的方法名以findBy開頭的方法抓取,我是查詢之後抓取。使用@AfterReturning註解