我正在做一个项目,其中我们有很多实体,我们将对其进行 CRUD 操作。我创建了一个基本实体类,并且在所有其他实体中我扩展了基本实体类,该类具有公共(public)字段,如created_date、created_by、last_updated_date、last_updated_by 等。现在,我想在 Spring CrudRepository 方法上实现方面并设置上述内容保存时提到的字段。
我尝试过实现类似的东西,但不起作用。
package com.cerium.aop;
import java.util.Date;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.cerium.datamodel.AccountDataModel;
import com.cerium.domain.Account;
import com.cerium.domain.BaseEntity;
import com.cerium.util.Constants;
/**
* @author Manikanta B Cerium
*
*/
@Component
@Aspect
public class SampleAspect {
private static final Logger LOG = LoggerFactory.getLogger(SampleAspect.class);
@Around("execution(* com.cerium.repository.*.save (com.cerium.domain.BaseEntity)) && args(saveData)")
public Object beforeSave(ProceedingJoinPoint proceedingJoinPoint, Object saveData) throws Throwable {
LOG.debug("Into aspect before save: {}", saveData);
BaseEntity baseEntity = (BaseEntity) proceedingJoinPoint.proceed(new Object[] { saveData });
// set the fields here......
baseEntity.setCreatedDate(new Date());
System.out.println(saveData);
return baseEntity;
}
}
最佳答案
要使用方面,我们应该首先使用过滤器表达式定义一个切入点方法(在您的情况下为“保存”方法),然后创建一个方法来处理此切入点:
@Component
@Aspect
public class CommonSaveAspect {
@Pointcut("execution(* com.cerium.repository.*.save(..))")
public void commonSave() {
}
@Around("commonSave()")
public Object addCommonData(final ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
if (Iterable.class.isAssignableFrom(args[0].getClass())) {
//noinspection unchecked
Iterable<BaseEntity> entities = (Iterable<BaseEntity>) args[0];
entities.forEach(entity -> {
// set the fields here...
});
}
if (args[0] instanceof BaseEntity) {
BaseEntity entity = (BaseEntity) args[0];
// set the fields here...
}
return pjp.proceed(args);
}
}
关于spring-boot - 如何在 Spring 增删改查存储库方法上实现 Aspect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041594/