从AspectJ ProceedingJoinPoint获取Springbean
我希望使用AspectJ获得Spring数据存储库接口或调用bean的从AspectJ ProceedingJoinPoint获取Springbean,spring,spring-boot,spring-data,aspectj,Spring,Spring Boot,Spring Data,Aspectj,我希望使用AspectJ获得Spring数据存储库接口或调用bean的void delete(id),该函数的问题是没有参数或返回类型来猜测bean,是否知道如何从AspectJ ProceedingJoinPoint获取调用bean或接口名 这是我的实际代码: @Pointcut("execution(public * org.springframework.data.repository.Repository+.save(..)) || execution(public * org.spri
void delete(id)
,该函数的问题是没有参数或返回类型来猜测bean,是否知道如何从AspectJ ProceedingJoinPoint获取调用bean或接口名
这是我的实际代码:
@Pointcut("execution(public * org.springframework.data.repository.Repository+.save(..)) || execution(public * org.springframework.data.repository.Repository+.delete(..)) && target(repository)")
public void publicNonVoidRepositoryMethod(CrudRepository repository) {
}
@Around("publicNonVoidRepositoryMethod(CrudRepository repository)")
public Object publicNonVoidRepositoryMethod(ProceedingJoinPoint pjp , CrudRepository repository) throws Throwable {
.......
}
您可以添加目标参数以获取已调用的存储库:
@Aspect
@Component
public class SampleAspect {
// Apply to all repositories in package repositories
@After("execution(* repositories.*.delete(*)) && target(repository) && args(id)")
public void afterEntityDelete(CrudRepository repository, Object id) {
...
}
}
这是一个老生常谈的问题,但有些人可能会觉得这很有帮助
- 为CRUDEPository、Paging和SortingRepository等上的所有删除方法声明切入点:
- 从代码调用时,可以传递实体本身
- 另一方面,当通过springdatarest调用delete方法时,使用ID(在本例中为Long)调用delete方法
可识别的接口,以便轻松访问getId()
:
谢谢你的回答,但我试着根据我自己的情况调整它,但不起作用,你能检查一下我上面的代码吗。老实说,我不确定,我对获得目标的@Before
和@Before
有很好的经验-这种解决方案根本不需要@Poincut
。到目前为止,我还没有弄清楚如何在@周围设置它。
@Pointcut("execution(* org.springframework.data.repository.*.delete(..)) && args(entity)")
public void repoDelete(Object entity) {}
@Around(value="repoDelete(entity)",argNames="entity")
public void onDelete(ProceedingJoinPoint pjp, Object entity) throws Throwable{
String invoker = null; //this will become the type name
Long entityId = 0L;
if (entity.getClass().getName().equals("java.lang.Long")){
entityId = (Long)entity;
REFLECT: {
// this returns a list of JPA repository-related interfaces
Class[] interfaces = jp.getTarget().getClass().getInterfaces();
for (Class iface: interfaces) {
// one of them is your JPA repository
if (iface.getName().startsWith("YOUR REPO PACKAGE")){
// the entity type can be accessed via generics
ParameterizedType pType = (ParameterizedType) iface.getGenericInterfaces()[0];
// this list contains two values - the entity type and the identifier type
Type[] typeArgs = pType.getActualTypeArguments();
for (Type t: typeArgs) {
if (t.getTypeName().startsWith("YOUR ENTITY PACKAGE")) {
invoker = t.getTypeName();
break REFLECT;
}
}
}
}
}
} else {
invoker = entity.getClass().getName();
if (entity instanceof Identifiable) entityId = (Long) ((Identifiable) entity).getId();
}
// do whatever you need ...
pjp.proceed();
}