hibernate-envers RevisionListener spring 集成为 spring bean
Posted
技术标签:
【中文标题】hibernate-envers RevisionListener spring 集成为 spring bean【英文标题】:hibernate-envers RevisionListener spring integration as spring bean 【发布时间】:2012-01-21 03:15:04 【问题描述】:我需要在 hibernate-envers 的修订监听器中做一些数据库处理。为此,我需要 Spring Framework 的注入功能。如何实施?这是表示需要的代码,但 CustomRevisionListener 由 Envers 代码中的构造函数实例化。 Spring 只有SecurityContextHolder
作为静态服务定位器。如何注入其他bean?
@Service
public class CustomRevisionListener implements EntityTrackingRevisionListener
@Resource
private PersistenceManagerHibernate persistenceManagerHibernate;
public void newRevision(Object revisionEntity)
CustomRevisionEntity revision = (CustomRevisionEntity) revisionEntity;
revision.setUsername(getUsername());
public String getUsername()
final SecurityContext context = SecurityContextHolder.getContext();
if (context != null)
if (context.getAuthentication() != null)
return context.getAuthentication().getName();
else
return "anonymous";
return "anonymous";
@Override
public void entityChanged(@SuppressWarnings("rawtypes") Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, Object revisionEntity)
CustomRevisionEntity revision = (CustomRevisionEntity) revisionEntity;
revision.setEntityId(entityId.toString());
revision.setEntityName(entityName);
revision.setRevisionType((int)revisionType.getRepresentation());
Auditable auditable = null;
if (entityId instanceof Long)
auditable = persistenceManagerHibernate.findById(entityClass, (Long)entityId);
revision.setGroupName(auditable.getAuditGroupName());
revision.setGroupEntityId(auditable.getAuditGroupId());
【问题讨论】:
【参考方案1】:由于 CustomRevisionListener 是由 Envers 中的构造函数实例化的,因此您必须找到另一种方法来检索 Spring 托管 bean 的句柄。
您可以创建一个实用程序类来实现此目的:
/**
* Utility class which provides lookup services for Spring managed beans from
* within unmanaged beans.
*/
@Component
public class ContextLookup implements ApplicationContextAware
private static ApplicationContext sApplicationContext;
@Override
public void setApplicationContext( ApplicationContext aApplicationContext )
throws BeansException
setContext( aApplicationContext );
public static void setContext( ApplicationContext aApplicationContext )
sApplicationContext = aApplicationContext;
protected static ApplicationContext getApplicationContext()
return sApplicationContext;
public static Object getBean( String aName )
if ( sApplicationContext != null )
return sApplicationContext.getBean( aName );
return null;
public static <T> T getBean( Class<T> aClass )
if ( sApplicationContext != null )
return sApplicationContext.getBean( aClass );
return null;
在您的 CustomRevisionListener 中
public class CustomRevisionListener
public void myMethod()
..
// get a handle to your spring managed bean
Foo foo = (Foo)ContextLookup.getBean( "mySpringManagedBean" );
..
【讨论】:
以上是关于hibernate-envers RevisionListener spring 集成为 spring bean的主要内容,如果未能解决你的问题,请参考以下文章
SVN中Revert changes from this revision 跟Revert to this revision