一、整合拦截器
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
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
添加数据库连接池的配置
三、整合Mybait
pom
需要MySQL驱动依赖
<!-- Mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--Mybaits-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
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<Label> findAll(){
return service.findAll();
}
@GetMapping("/id")
public Label findById(String id){
return service.findById(id);
}
@GetMapping("/findByKeyword")
public List<Label> findByKeyword(String labelname){
return service.findByKeyword(labelname);
}
@PostMapping("/findByKeywords")
public List<Label> findByKeywords(@RequestBody Label label){
return service.findByKeywords(label);
}
@PostMapping
public void add(@RequestBody Label label){
service.add(label);
}
@PutMapping
public void update(@RequestBody Label label){
service.upadte(label);
}
@DeleteMapping
public void del(String id){
service.deleteById(id);
}
}
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<Label> findAll(){
return baseMapper.findAll();
}
public Label findById(String id){
return baseMapper.findById(id);
}
public List<Label> findByKeyword(String label){
return baseMapper.findByKeyword(label);
}
public List<Label> findByKeywords(Label label){
return baseMapper.findByKeysords(label.getLabelname(),label.getFans());
}
public void add(Label label){
baseMapper.addLabel(label);
}
public void upadte(Label label){
baseMapper.updateLabel(label);
}
public void deleteById(String id){
baseMapper.deleteById(id);
}
}
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<Label> findAll();
@Select("SELECT * FROM `tb_label` WHERE `id` = #{id}")
Label findById(String id);
/**
* 模糊查询 -
* 因为#{} 取值出会自带引号,${}取值就是去除原值,当参数是基本数据类型,其中必须是value
* @param labelname
* @return
*/
@Select("SELECT * FROM `tb_label` WHERE `labelname` LIKE '%${value}%'")
List<Label> findByKeyword(String labelname);
/**
* Mapper接口方法中多个参数,想要注入到SQL语句中,需要使用注解@Param
* @param labelname
* @param fans
* @return
*/
@Select("SELECT * FROM `tb_label` WHERE `labelname` LIKE '%${labelname}%' AND `fans` LIKE '%${fans}%'")
List<Label> findByKeysords(@Param("labelname") String labelname,@Param("fans") String fans);
/**
* 添加
* @param label
*/
@Insert("INSERT INTO `tb_label` VALUES (#{id},#{labelname},#{state},#{count},#{recommend},#{fans})")
void addLabel (Label label);
/**
* 更新
* @param label
*/
@Update("UPDATE `tb_label` SET `labelname` = #{labelname} ,`state` = #{state},`count`=#{count},`recommend`=#{recommend},`fans`=#{fans} WHERE `id` = #{id}")
void updateLabel(Label label);
/**
* 删除
* @param id
*/
@Delete("DELETE FROM `tb_label` WHERE `id` = #{id}")
void deleteById(String id);
}
使用mapper.xml配置文件形式
mybatis-config.xml配置文件
写mybatis-config.xml配置文件,放在/resources/mybatis/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 上面的dtd是当前这个xml文件的约束,类似于spring的xsd约束 -->
<configuration>
<!-- 此处的一些列配置: ssm整合后,都可以交给spring去配置 -->
<!-- 设置别名
该包下的所有类都有别名
别名就是该类的类名(大小写均可)
-->
<settings><!-- 使用驼峰命名法转换字段-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.lsh.model.*"/>
</typeAliases>
</configuration>
Mapper接口
# UserMapper
public interface UserMapper {
List<User> findAllLabelByMapperXML() ;
}
# BaseMapper
public interface BaseMapper {
List<Label> findAllLabelByMapperXML();
}
Mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lsh.mapper.db1.BaseMapper" >
<select id="findAllLabelByMapperXML" resultType="com.lsh.model.Label">
SELECT * FROM `tb_label`
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lsh.mapper.db2.UserMapper" >
<select id="findAllLabelByMapperXML" resultType="com.lsh.model.User">
select * from `tb_user`
</select>
</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接口类。
在resource目录下新建mybatis/mapper/,新建db1和db2,用来存放Mapper.xml文件。
Bug 别名无效
设置别名无效,报错找不到类
解决办法:需要写全路径。
作者:Liu_Shihao
原文链接:https://blog.csdn.net/DreamsArchitects/article/details/109511132