How to automatically set date_created using spring aop
i've been working on a project in java+maven+spring+hibernate and i wanted to automatically assign the current date to the POJOs before the calling of saveorupdate. i wouldn't mind creating new Date()
for all the date_created of all the classes but they are just plenty.
I've just discovered that spring aop is good at those things.
//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.m开发者_运维知识库odel.*",
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**/
}
}
Can anyone show me what i'm doing wrong here?Or this is just he wrong way to achieve what i wanted to do.Thanks for reading
If you are using Hibernate, you can use entity listeners to set the property before persisting it in the database.
All you need is a pre-persist listener that sets the creation date to new Date()
.
Here is the Hibernate documentation on entity listeners.
精彩评论