有没有办法从 Spring AOP 建议中持久化 JPA 实体?每当我尝试这样做时,都会收到错误 java.lang.NoSuchMethodError。我猜这可能是因为我的 persistence.xml 配置在运行时部署了 JPA 基础架构。
弹簧配置:
<aop:aspect ref="attachmentCreatorAdvice">
<aop:pointcut expression="execution(* com.mycomp.core.eventhandlers.*.handle*CreatedEvent(..) )" id="attachmentCreatorPointcut"/>
<aop:after-returning method="create"
pointcut-ref="attachmentCreatorPointcut" />
</aop:aspect>
AttachmentCreatorAdvice 代码:
private AttachmentDao attachmentDao;
public AttachmentDao getAttachmentDao() {
return attachmentDao;
}
public void setAttachmentDao(AttachmentDao attachmentDao) {
this.attachmentDao = attachmentDao;
}
public void create(JoinPoint jp) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Event event = (Event) jp.getArgs()[0];
Field f = event.getClass().getDeclaredField("attachments");
if ( f != null ) {
f.setAccessible(true);
List<Attachment> attachments = (List<Attachment>) f.get(event);
Field id = event.getClass().getDeclaredField("id");
if ( id != null) {
id.setAccessible(true);
AggregateIdentifier uuid = (AggregateIdentifier) id.get(event);
for( Attachment attachment : attachments ) {
AttachmentDto newAttachment = new AttachmentDto();
newAttachment.setId(UUID.randomUUID().toString());
newAttachment.setElementId(uuid.asString());
newAttachment.setDescription(attachment.getDescription());
newAttachment.setFilename(attachment.getFilename());
newAttachment.setFilesize(attachment.getFilesize());
newAttachment.setFiletype(attachment.getFiletype());
newAttachment.setLink(attachment.getLink());
newAttachment.setAttachmentBlob(DecodeUtils.fromBase64(attachment.getAttachmentBlob()));
attachmentDao.save(newAttachment);
}
}
}
}
attachDao 是从 Spring 容器中注入的。AttachmentDto 从 AbstractDto 扩展而来。
@MappedSuperclass
public abstract class AbstractDto<T> implements Serializable {
@Override
public boolean equals(Object obj) {
boolean equals = false;
if ( obj instanceof AbstractDto ) {
AbstractDto o = (AbstractDto) obj;
if ( o.getId().equals( this.id ) ) {
equals = true;
}
} else {
equals = false;
}
return equals;
}
@Id
private T id;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
调用 attachmentDao.save 方法时,出现以下错误:
[EL Severe]: ejb: 2012-12-17 16:12:17.579--ServerSession(30266940)--Thread(Thread[main,5,main])--java.lang.NoSuchMethodError com.mycomp.core.data.dto.AbstractDto <init>
希望有帮助。
干杯