第一步,引入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注解