JAVA专题---SpringBoot intercept拦截器中获取JPA数据库操作实例

使用“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;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,584评论 1 92
  • 1.1 spring IoC容器和beans的简介 Spring 框架的最核心基础的功能是IoC(控制反转)容器,...
    simoscode阅读 6,751评论 2 22
  • SpringMVC原理分析 Spring Boot学习 5、Hello World探究 1、POM文件 1、父项目...
    jack_jerry阅读 1,362评论 0 1
  • 小时候的事情就不提了,出了社会后,我的父母就只希望我饿不死,冻不死,安于现状,似乎只有这样,他们心里才会踏实!不考...
    銥然阅读 194评论 0 1