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等都可使用了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
在Spring Boot使用MyBatis拦截拦截特定的Mapper方法,你可以通过实现`Interceptor`接口来创建自定义的拦截,并在拦截定义你想要的逻辑。以下是一个示例: 首先,创建一个实现了`Interceptor`接口的自定义拦截类,例如`MyInterceptor`。在该类,你可以重写`intercept`方法,在方法内部实现你的拦截逻辑。例如,下面的示例通过判断Mapper类型来拦截特定的Mapper方法: ```java @Intercepts({ @Signature(type = UserMapper.class, method = "getUserById", args = {Long.class}) }) public class MyInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 在这里实现你的拦截逻辑 System.out.println("Before getUserById method"); // 继续执行被拦截的方法 Object result = invocation.proceed(); // 在这里实现你的拦截逻辑 System.out.println("After getUserById method"); return result; } } ``` 然后,在你的Spring Boot配置类将自定义拦截添加到MyBatis的配置。例如: ```java @Configuration public class MyBatisConfig { @Autowired private MyInterceptor myInterceptor; @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); // 添加自定义拦截 Interceptor[] interceptors = new Interceptor[]{myInterceptor}; sessionFactory.setPlugins(interceptors); return sessionFactory.getObject(); } } ``` 在上述示例,我们将自定义拦截`MyInterceptor`添加到了MyBatis的配置,并通过`setPlugins`方法设置了拦截。这样,当调用`UserMapper`接口的`getUserById`方法时,拦截拦截逻辑就会被触发。 需要注意的是,上述示例拦截了`UserMapper`接口的`getUserById`方法,你可以根据自己的需求,通过修改`@Signature`注解的参数来拦截其他的Mapper方法。另外,你也可以创建多个自定义拦截,并将它们按照需要添加到MyBatis配置

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦里藍天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值