提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.datapermission.core.aop; |
H |
2 |
|
|
3 |
import com.iailab.framework.datapermission.core.annotation.DataPermission; |
|
4 |
import lombok.Getter; |
|
5 |
import org.aopalliance.intercept.MethodInterceptor; |
|
6 |
import org.aopalliance.intercept.MethodInvocation; |
|
7 |
import org.springframework.core.MethodClassKey; |
|
8 |
import org.springframework.core.annotation.AnnotationUtils; |
|
9 |
|
|
10 |
import java.lang.reflect.Method; |
|
11 |
import java.util.Map; |
|
12 |
import java.util.concurrent.ConcurrentHashMap; |
|
13 |
|
|
14 |
/** |
|
15 |
* {@link DataPermission} 注解的拦截器 |
|
16 |
* 1. 在执行方法前,将 @DataPermission 注解入栈 |
|
17 |
* 2. 在执行方法后,将 @DataPermission 注解出栈 |
|
18 |
* |
|
19 |
* @author iailab |
|
20 |
*/ |
|
21 |
@DataPermission // 该注解,用于 {@link DATA_PERMISSION_NULL} 的空对象 |
|
22 |
public class DataPermissionAnnotationInterceptor implements MethodInterceptor { |
|
23 |
|
|
24 |
/** |
|
25 |
* DataPermission 空对象,用于方法无 {@link DataPermission} 注解时,使用 DATA_PERMISSION_NULL 进行占位 |
|
26 |
*/ |
|
27 |
static final DataPermission DATA_PERMISSION_NULL = DataPermissionAnnotationInterceptor.class.getAnnotation(DataPermission.class); |
|
28 |
|
|
29 |
@Getter |
|
30 |
private final Map<MethodClassKey, DataPermission> dataPermissionCache = new ConcurrentHashMap<>(); |
|
31 |
|
|
32 |
@Override |
|
33 |
public Object invoke(MethodInvocation methodInvocation) throws Throwable { |
|
34 |
// 入栈 |
|
35 |
DataPermission dataPermission = this.findAnnotation(methodInvocation); |
|
36 |
if (dataPermission != null) { |
|
37 |
DataPermissionContextHolder.add(dataPermission); |
|
38 |
} |
|
39 |
try { |
|
40 |
// 执行逻辑 |
|
41 |
return methodInvocation.proceed(); |
|
42 |
} finally { |
|
43 |
// 出栈 |
|
44 |
if (dataPermission != null) { |
|
45 |
DataPermissionContextHolder.remove(); |
|
46 |
} |
|
47 |
} |
|
48 |
} |
|
49 |
|
|
50 |
private DataPermission findAnnotation(MethodInvocation methodInvocation) { |
|
51 |
// 1. 从缓存中获取 |
|
52 |
Method method = methodInvocation.getMethod(); |
|
53 |
Object targetObject = methodInvocation.getThis(); |
|
54 |
Class<?> clazz = targetObject != null ? targetObject.getClass() : method.getDeclaringClass(); |
|
55 |
MethodClassKey methodClassKey = new MethodClassKey(method, clazz); |
|
56 |
DataPermission dataPermission = dataPermissionCache.get(methodClassKey); |
|
57 |
if (dataPermission != null) { |
|
58 |
return dataPermission != DATA_PERMISSION_NULL ? dataPermission : null; |
|
59 |
} |
|
60 |
|
|
61 |
// 2.1 从方法中获取 |
|
62 |
dataPermission = AnnotationUtils.findAnnotation(method, DataPermission.class); |
|
63 |
// 2.2 从类上获取 |
|
64 |
if (dataPermission == null) { |
|
65 |
dataPermission = AnnotationUtils.findAnnotation(clazz, DataPermission.class); |
|
66 |
} |
|
67 |
// 2.3 添加到缓存中 |
|
68 |
dataPermissionCache.put(methodClassKey, dataPermission != null ? dataPermission : DATA_PERMISSION_NULL); |
|
69 |
return dataPermission; |
|
70 |
} |
|
71 |
|
|
72 |
} |