我有以下JPA实体,我想使用@PrePersist和@PreUpdate来方便使用Spring上下文中的当前用户设置lastUpdatedBy String,但我不知道如何访问该信息来自实体层面的上下文。有任何想法吗?
public abstract class BaseEntity {
private Date createdDate;
private String lastUpdatedBy;
@Column(name = "LAST_UPDATED_BY")
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="CREATED_DATE")
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date created) {
if (created != null) {
this.createdDate = created;
}
}
@PrePersist
protected void onCreate() {
createdDate = new Date();
//lastUpdatedBy = //need to access Spring user here
}
@PreUpdate
public void onUpdate() {
updatedDate = new Date();
//lastUpdatedBy = //need to access Spring user here
}
}
答案 0 :(得分:2)
解决方案可以是Good way to access Spring singleton from within domain objects?中定义的解决方案来访问Spring上下文
在您的上下文中定义一个CurrentUserHolder
bean,定义为使用ApplicationContext.getBean()
在@ Pre / @ Post函数中访问的单例bean。
CurrentUserHolder
bean包含当前用户名,其值为mantained来自应用程序(可在启动后或用户更换后设置)
在Spring-batch中,这是跨步骤传递数据的常用解决方案。