代码之家  ›  专栏  ›  技术社区  ›  black sensei

如何使用spring aop自动设置创建日期

  •  0
  • black sensei  · 技术社区  · 15 年前

    我一直在用java+maven+spring+hibernate开发一个项目,我想在调用saveorupdate之前自动将当前日期分配给pojo。我不介意创造 new Date()

    //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**/
        }
    }
    

    有人能告诉我我做错了什么吗?或者这是他实现我梦想的错误方式好的。谢谢为了阅读

    1 回复  |  直到 9 年前
        1
  •  1
  •   Vivien Barousse    15 年前

    如果您使用的是Hibernate,那么在将属性持久化到数据库之前,可以使用实体侦听器来设置属性。

    您所需要的只是一个预持久化侦听器,它将创建日期设置为 new Date() .

    这是你的名字 Hibernate documentation on entity listeners .