我一直在 java+maven+spring+hibernate 中开发一个项目,我想在调用 saveorupdate 之前自动将当前日期分配给 POJO。我不介意为所有类的所有 date_created 创建 new Date()
,但它们已经足够了。
我刚刚发现 spring aop 擅长这些事情。
在谷歌上几分钟后,我找到了一个很好的方法。但是到目前为止,我不知道如何准确地将新日期分配给 POJO,然后 POJO 是我的介绍接口(interface)的实现类。我真的不知道如何让它有意义。所以根据我的理解,这就是我会做的:
//DateSetter.java
package org.personal.myproject.model;
import java.util.Date;
//this is how i'm getting the current date
public interface DateSetter {
public Date getCurrentDate();
}
//DateCreatedDateSetterImpl.java
package org.personal.myproject.model;
import java.util.Date;
// the implementation
public class DateCreatedDateSetterImpl implements DateSetter {
public Date getCurrentDate() {
return new Date();
}
}
//DateIntroduction.java
package org.personal.myproject.model;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareParents;
@Aspect
public class DateIntroduction {
//making all the model implementors of the DateSetter interface
@DeclareParents(value="org.personal.myproject.model.*",
defaultImpl=DateCreatedDateSetterImpll.class)
public DateSetter dateSetter;
/**here is to add my "before trigger" for every calling of every method.
if you can see i have the daos in 2 packages, i don't know whether is wrong or not.i'm actually using the generic Dao so should i use that interface instead?
**/
@Before("execution * org.personal.myproject.dao.hibernate.*.(..) || * org.personal.myproject.dao.hibernate.*.*.(..)" + "&& this(dateSetter)")
public void injectLastModifiedDate(DateSetter dateSetter){
/**so here i'm expecting to inject the new date but apparently i'm missing something**/
}
}
任何人都可以告诉我我在这里做错了什么吗?或者这只是他实现我想做的事情的错误方法。感谢您的阅读
最佳答案
如果您使用 Hibernate,则可以使用实体监听器来设置属性,然后再将其保留在数据库中。
您所需要的只是一个将创建日期设置为 new Date()
的预持久监听器。
关于java - 如何使用spring aop自动设置date_created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702568/