spring中JoinPoint的使用

来源:互联网 发布:欧洲卡车模拟2优化 编辑:程序博客网 时间:2024/05/20 23:56
AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,如果是环绕增强时,使用org.aspectj.lang.ProceedingJoinPoint表示连接点对象,该类是JoinPoint的子接口。任何一个增强方法都可以通过将第一个入参声明为JoinPoint访问到连接点上下文的信息。我们先来了解一下这两个接口的主要方法: 
1)JoinPoint 
 java.lang.Object[] getArgs():获取连接点方法运行时的入参列表; 
 Signature getSignature() :获取连接点的方法签名对象; 
 java.lang.Object getTarget() :获取连接点所在的目标对象; 
 java.lang.Object getThis() :获取代理对象本身; 
2)ProceedingJoinPoint 
ProceedingJoinPoint继承JoinPoint子接口,它新增了两个用于执行连接点方法的方法: 
 java.lang.Object proceed() throws java.lang.Throwable:通过反射执行目标对象的连接点处的方法; 

 java.lang.Object proceed(java.lang.Object[] args) throws java.lang.Throwable:通过反射执行目标对象连接点处的方法,不过使用新的入参替换原来的入参。 


示例代码:

public class DataSourceAspect {
public void intercept(JoinPoint point) throws Exception {
Class<?> target = point.getTarget().getClass();
MethodSignature signature = (MethodSignature) point.getSignature();
for (Class<?> clazz : target.getInterfaces()) {
resolveDataSource(clazz, signature.getMethod());
}
resolveDataSource(target, signature.getMethod());
}


private void resolveDataSource(Class<?> clazz, Method method) {
try {
Class<?>[] types = method.getParameterTypes();
if (clazz.isAnnotationPresent(DataSource.class)) {
DataSource source = clazz.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}


Method m = clazz.getMethod(method.getName(), types);
if (m != null) {
Annotation data = m.getAnnotation(DataSource.class);
/* Annotation data = method.getAnnotation(DataSource.class); */
if (data != null) {
DataSource source = (DataSource) data;
DynamicDataSourceHolder.setDataSource(source.value());
}
}


} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

原创粉丝点击