我正在做一个项目,其中我们有许多实体,我们将在其上进行CRUD操作。我已经创建了一个基本实体类,并且在所有其他实体中我扩展了基本实体类,它具有common_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;
}
}
答案 0 :(得分:2)
要使用方面,首先应使用过滤器表达式定义切入点方法(在您的情况下为'保存'方法),然后创建一个方法来处理此切入点:
@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);
}
}