资讯专栏INFORMATION COLUMN

Springboot整合Hibernate拦截器时无法向拦截器注入Bean

DangoSky / 3050人阅读

摘要:同时注释配置失败的构造方法触发了两次,添加到中的实例和注册到容器中的实例并不是同一个实例解决方法增加一个获取的实例的工具类,通过这个工具类调用需要注入的服务的方法工具类修改拦截器执行结果

开发环境

JDK 1.8

Springboot 2.1.1.RELEASE

pom配置
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.1.RELEASE
         
    
    
    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
            mysql
            mysql-connector-java
            8.0.13
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
关键代码 实体类
@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Repository
public interface UserRepository extends JpaRepository {

}
自定义服务
@Service
public class MyService {

    public void print(){
        System.out.println(this.getClass().getSimpleName()+" call");
    }
}
拦截器
public class SimpleInterceptor extends EmptyInterceptor {

    @Resource
    private MyService myService;

    @Override
    public String onPrepareStatement(String sql) {
        myService.print();
        System.out.println("sql:"+sql);
        return super.onPrepareStatement(sql);
    }
}
启动类
@SpringBootApplication
public class BootHibernateInterceptorProblemApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootHibernateInterceptorProblemApplication.class, args);
    }

}
配置
## DataSource
spring.datasource.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456789

## hibernate
spring.jpa.hibernate.ddl-auto=update
## add interceptor
spring.jpa.properties.hibernate.ejb.interceptor=com.rjh.interceptor.SimpleInterceptor
单元测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class BootHibernateInterceptorProblemApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Test
    public void contextLoads() {
        System.out.println(userRepository.findAll());
    }

}
运行结果
java.lang.NullPointerException
    at com.rjh.interceptor.SimpleInterceptor.onPrepareStatement(SimpleInterceptor.java:20)
    ...
    ...
    ...
分析

根据异常信息,猜测是注入MyService失败

修改单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class BootHibernateInterceptorProblemApplicationTests {

    @Resource
    private UserRepository userRepository;

    @Resource
    private MyService myService;

    @Resource
    private SimpleInterceptor simpleInterceptor;

    @Test
    public void contextLoads() {
        Assert.assertNotNull(myService);
        Assert.assertNotNull(simpleInterceptor);
        System.out.println(userRepository.findAll());
    }

}
运行结果
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type "com.rjh.interceptor.SimpleInterceptor" available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    ...
分析

根据异常信息可知,Spring的IoC容器中并没有SimpleInterceptor这个Bean,从此处可知spring.jpa.properties.hibernate.ejb.interceptor=com.rjh.interceptor.SimpleInterceptor并没有把这个拦截器注册到Spring容器中

失败方案

SimpleInterceptor上添加@Component注解,将SimpleInterceptor注册到Spring容器中。同时注释spring.jpa.properties.hibernate.ejb.interceptor配置

失败:SimpleInterceptor的构造方法触发了两次,添加到Hibernate中的SimpleInterceptor实例和注册到Spring容器中的SimpleInterceptor实例并不是同一个实例

解决方法

增加一个获取Spring的ApplicationContext实例的工具类,通过这个工具类调用需要注入的服务的方法

工具类
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext=applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
修改拦截器
public class SimpleInterceptor extends EmptyInterceptor {

    @Override
    public String onPrepareStatement(String sql) {
        MyService myService= SpringContextUtil.getApplicationContext().getBean(MyService.class);
        myService.print();
        System.out.println("sql:"+sql);
        return super.onPrepareStatement(sql);
    }

}
执行结果
MyService call
sql:select user0_.id as id1_0_, user0_.name as name2_0_ from user user0_
[]

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75061.html

相关文章

  • SpringBoot就是这么简单

    摘要:热加载代表的是我们不需要重启服务器,就能够类检测得到,重新生成类的字节码文件无论是热部署或者是热加载都是基于类加载器来完成的。验证阶段字节码文件不会对造成危害准备阶段是会赋初始值,并不是程序中的值。 一、SpringBoot入门 今天在慕课网中看见了Spring Boot这么一个教程,这个Spring Boot作为JavaWeb的学习者肯定至少会听过,但我是不知道他是什么玩意。 只是大...

    whinc 评论0 收藏0
  • 第三十五章:SpringBoot与单元测试的小秘密

    摘要:本章目的基于平台整合分别完成客户端服务端的单元测试。在测试控制器内添加了三个测试方法,我们接下来开始编写单元测试代码。总结本章主要介绍了基于平台的两种单元测试方式,一种是在服务端采用注入方式将需要测试的或者注入到测试类中,然后调用方法即可。 单元测试对于开发人员来说是非常熟悉的,我们每天的工作也都是围绕着开发与测试进行的,在最早的时候测试都是采用工具Debug模式进行调试程序,后来Ju...

    hikui 评论0 收藏0
  • Java3y文章目录导航

    摘要:前言由于写的文章已经是有点多了,为了自己和大家的检索方便,于是我就做了这么一个博客导航。 前言 由于写的文章已经是有点多了,为了自己和大家的检索方便,于是我就做了这么一个博客导航。 由于更新比较频繁,因此隔一段时间才会更新目录导航哦~想要获取最新原创的技术文章欢迎关注我的公众号:Java3y Java3y文章目录导航 Java基础 泛型就这么简单 注解就这么简单 Druid数据库连接池...

    KevinYan 评论0 收藏0
  • springboot整合shiro使用shiro-spring-boot-web-starter

    摘要:此文章仅仅说明在整合时的一些坑并不是教程增加依赖集成依赖配置三个必须的用于授权和登录创建自己的实例用于实现权限三种方式实现定义权限路径第一种使用角色名定义第二种使用权限定义第三种使用接口的自定义配置此处配置之后需要在对应的 此文章仅仅说明在springboot整合shiro时的一些坑,并不是教程 增加依赖 org.apache.shiro shiro-spring-...

    sevi_stuo 评论0 收藏0
  • ★推荐一款适用于SpringBoot项目的轻量级HTTP客户端框架

    摘要:请求重试拦截器错误解码器在发生请求错误包括发生异常或者响应数据不符合预期的时候,错误解码器可将相关信息解码到自定义异常中。 在SpringBoot项目直接使用okhttp、httpClient或者RestTemplate发起HTTP请求,既繁琐又不方便统一管理。因此,在这里推荐一个适...

    不知名网友 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<