SpringBoot如何整合SpringMVC的拦截器、数据源、Mybatis以及配置多数据源?

一、整合拦截器

1. 创建自定义拦截器

package com.lsh.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author :LiuShihao
 * @date :Created in 2020/11/5 2:10 下午
 * @desc :
 */
// 该注解使类被Spring容器托管
@Component 
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 重新方法: 拦截请求,获得登录信息
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor -url= "+request.getRequestURL());
        return true;
    }
}

2. Config配置类

package com.lsh.config;

import com.lsh.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author :LiuShihao
 * @date :Created in 2020/11/5 2:12 下午
 * @desc :
 */
// 该注解说明该类是一个Spring的配置类,相当于是之前的配置文件
@Configuration 
public class MyInterceptorConfig implements WebMvcConfigurer {

    /**
     * 注意实现了接口
     * 重新添加拦截路径的方法
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 将自己的拦截器注册进运行环境中
        InterceptorRegistration registration = registry.addInterceptor(new MyInterceptor());
        // /* 匹配单层路径 /a 或者/b 可以拦截到 ,/a/b/c 这样的多层路径不会拦截
        // /** 匹配单层路径 /a 或者/b 多层路径/a/b/c 都可以
        // 支持后缀匹配.注意不是*.do 而是 /*.do
        // 支持路径中的模糊匹配 /user/**
        registration.addPathPatterns("/base/**");
        // 添加一些不拦截路径
        registration.excludePathPatterns("/login/**","/logout/**","/html/t1.html");
    }
}

二、整合数据源

C3P0 DBCP Driud等数据源.
SpringBoot默认使用HikariDataSource连接池,我们也可以自己指定连接池.
比如: 使用阿里巴巴的数据库连接池Driud

pom

        
            com.alibaba
            druid
            1.1.10
        

添加数据库连接池的配置


在这里插入图片描述

三、整合Mybait

pom

需要MySQL驱动依赖

            
        
            mysql
            mysql-connector-java
        
            
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.0
        

Controller

package com.lsh.controller;

import com.lsh.model.Label;
import com.lsh.service.Impl.MapperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author :LiuShihao
 * @date :Created in 2020/11/5 3:13 下午
 * @desc :
 */
@RequestMapping("/mybatis")
@RestController
public class BaseMapperController {
    @Autowired
    MapperService service;
    @GetMapping
    public List

Service

package com.lsh.service.Impl;

import com.lsh.mapper.BaseMapper;
import com.lsh.model.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author :LiuShihao
 * @date :Created in 2020/11/5 3:07 下午
 * @desc :
 */
@Service
public class MapperService {
    @Autowired
    BaseMapper baseMapper;

    public List

Mapper 接口(直接使用注解)

package com.lsh.mapper;

import com.lsh.model.Label;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author :LiuShihao
 * @date :Created in 2020/11/5 2:22 下午
 * @desc :
 */
//该注解说明该类就行相当于一个xxxMapper.xml文件
@Mapper
public interface BaseMapper {
    @Select("SELECT * FROM `tb_label`")
    List

使用mapper.xml配置文件形式

mybatis-config.xml配置文件

写mybatis-config.xml配置文件,放在/resources/mybatis/





    
    
    
        
    
    
        
    


Mapper接口

# UserMapper
public interface UserMapper {
    List findAllLabelByMapperXML() ;
}
# BaseMapper
public interface BaseMapper {

    List

Mapper映射文件





    







    


yml配置文件

server:
  port: 9001
spring:
  application:
    name: tensquare-base   #  服务名字,用于服务调用.不能写_ springcloud不识别
  datasource:
    db1:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://116.62.13.104:3306/tensquare_base?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF8
      username: root
      password: 123456
    db2:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://116.62.13.104:3306/tensquare_user?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF8
      username: root
      password: 123456
eureka:
  client:
    service-url:
      defaultZone: http://localhost:6868/eureka
mybatis:
  type-aliases-package: com.lsh.model.*
  mapper-locations: classpath:mybatis/mapper/**.xml
  config-location: classpath:mybatis/mybatis-config.xml

四、配置多数据源

结构

[图片上传失败...(image-a58487-1604660537654)]

第一个数据源Config配置类

package com.lsh.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author :LiuShihao
 * @date :Created in 2020/6/22 5:17 下午
 * @desc :数据源配置类
 */
@Slf4j
//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.lsh.mapper.db1", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSourceConfig1 {
    // 将这个对象放入Spring容器中
    @Bean(name = "test1DataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "test1SqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("mybatis/mapper/db1/**.xml"));
        return bean.getObject();
    }
    @Bean("test1SqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate test1sqlsessiontemplate(
            @Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
    public DataSourceConfig1(){
        log.info("加载1数据源配置");
    }
}

第二个数据源Config配置类

package com.lsh.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author :LiuShihao
 * @date :Created in 2020/6/22 5:17 下午
 * @desc :数据源配置类
 */
@Slf4j
//表示这个类为一个配置类
@Configuration
@MapperScan(basePackages = "com.lsh.mapper.db2", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSourceConfig2 {
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource getDateSource2() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("mybatis/mapper/db2/**.xml"));
        return bean.getObject();
    }
    @Bean("test2SqlSessionTemplate")
    public SqlSessionTemplate test2sqlsessiontemplate(
            @Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
    public DataSourceConfig2(){
        log.info("加载2数据源配置");
    }
}

分别在com.lsh.mapper包下新建db1和db2,用来放Mapper接口类。


image.png

在resource目录下新建mybatis/mapper/,新建db1和db2,用来存放Mapper.xml文件。


image.png

Bug 别名无效

设置别名无效,报错找不到类
解决办法:需要写全路径。

作者:Liu_Shihao
原文链接:https://blog.csdn.net/DreamsArchitects/article/details/109511132

你可能感兴趣的:(SpringBoot如何整合SpringMVC的拦截器、数据源、Mybatis以及配置多数据源?)