我正在使用Hibernate拦截器执行更新,并且需要Repository保存在数据库中。
我自动连接存储库,但无法正常工作。始终为null。这是我的代码:
@Component
public class AuditInterceptor extends EmptyInterceptor {
@Autowired
private LogsRepository repository;
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types) {
if(entity instanceof Personnel) {
for (int i = 0; i < propertyNames.length; i++) {
if(currentState[i] != previousState[i]) {
Log log = new Log();
log.setEntity("Personnel");
log.setIdEntity(id.toString());
log.setPropertyChanged(propertyNames[i] );
log.setOldValue(previousState[i] != null ? previousState[i].toString() : "");
log.setNewValue(currentState[i] != null ? currentState[i].toString() : "");
log.setTimestamp(new Date());
System.out.println(log.toString());
repository.save(log);
return true;
}
System.out.println("Property names :"+propertyNames[i]);
System.out.println("Old value :"+previousState[i]);
System.out.println("New value :"+currentState[i]);
}
}
return false;
}
}
拦截器工作正常,但LogRepository始终为空。
答案 0 :(得分:1)
我通过实现ApplicationContextAware解决了这个问题
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext context;
public static <T extends Object> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringContext.context = context;
}
}
用法
LogsRepository repository = SpringContext.getBean(LogsRepository.class);