使用“org.springframework.web.context.support.WebApplicationContextUtils;”类
这个工具类可以通过HttpServletRequest请求对象的上下文(ServetCotext)获取Spring管理的Bean
private <T> T getMapper(Class<T> clazz,HttpServletRequest request)
{
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
return factory.getBean(clazz);
}
使用时
SystemLogRepository systemLogRepository = getMapper(SystemLogRepository.class,arg0);
获取了JPA接口实例,。save,findone,findAll等都可使用了。
举个栗子:
private <T> T getMapper(Class<T> clazz, HttpServletRequest request) {
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
return factory.getBean(clazz);
}
private boolean isSessionIdInvild(String sessionId, HttpServletRequest request) {
if (sessionServiceRepository == null)
sessionServiceRepository = getMapper(YtTbFontSiteUserEntityRepository.class, request);
if (sessionId != null && sessionId.length() > 0) {
YtTbFontSiteUserEntity usedFontSiteUserEntity = sessionServiceRepository.findOneBySessionId(sessionId, 0);
return usedFontSiteUserEntity != null && usedFontSiteUserEntity.getSessionInvildDateTime() != null && DateUtil.diffTimes(usedFontSiteUserEntity.getSessionInvildDateTime(), new Date(System.currentTimeMillis())) < 0;
}
return false;
}