栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

在springboot中一些框架集插件的配置

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在springboot中一些框架集插件的配置

spring基本环境搭建
  1. 创建springboot工程
  2. 创建基本配置和多环境配置
  3. 热部署
  4. 配置druid
  5. 配置swagger2
  6. 配置mybatisPlus
    1. 基本使用
    2. 自动生成工具
    3. 分页
1,创建工程

2,创建基本配置和多环境配置

在创建工程后直接运行会出现报错,如下

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
无法配置数据源:未指定“url”属性,无法配置嵌入的数据源。

所以我们需要进行基本环境配置

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/project_table?useSSL=false&useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
  profiles:
    # 当前环境
    active: dev

application-dev.yml

server:
  port: 8888
  servlet:
    # 默认为空,写后路径会变成127.0.0.1/项目路径/user/add
    context-path: /demo

运行无异常,定义个接口测试

package com.mall.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController  // 返回数据 等同于@Controller + @ResponseBody。
@CrossOrigin  // 解决跨域
@RequestMapping("/user")
public class UserController {
    @GetMapping("/login")
    public String login(){
        return  "hello,world";
    }
}

运行项目,访问指定连接,测试成功

3,配置热部署

1, pom.xml


    org.springframework.boot
    spring-boot-devtools

2, 设置中开启如下:建议全局设置

3,设置自动更新

4,配置druid

pom.xml

     
        
            com.alibaba
            druid-spring-boot-starter
            1.2.4
        

修改 application.yml

# 默认连接数据库方式
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/project_mall?useSSL=false&useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    # 设置类型,如果不适应druid连接池则不需要使用
    type: com.alibaba.druid.pool.DruidDataSource



# 第二种方式
#spring:
#  datasource:
#    druid:
#      driver-class-name: com.mysql.jdbc.Driver
#      url: jdbc:mysql://127.0.0.1:3306/project_mall?useSSL=false&useUnicode=true&characterEncoding=utf-8
#      username: root
#      password: root




重启运行;如下说明成功

5,配置swagger2

pom.xml


    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2

导入依赖后不能直接访问页面,需要启动,如果不启用会出现如下错误:

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:

创建配置类,启用swagger2

@Configuration  // 声明为配置类
@EnableSwagger2  // 启用
public class Swagger2Config {
}

启用后就能正常访问 :http://127.0.0.1:9999/swagger-ui.html出现页面,说明已经成功,不过我们需要把我们自己的信息写上去

Swagger2Config 常规配置

package com.project.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.documentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration  // 声明为配置类
@EnableSwagger2  // 启用
public class Swagger2Config {

    //配置文档信息
    private ApiInfo apiInfo() {
        Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱");
        return new ApiInfo(
                "商城接口", // 标题
                "用于商城接口的描述", // 描述
                "v1.0", // 版本
                "http://terms.service.url/组织链接", // 组织链接
                contact, // 联系人信息
                "Apach 2.0 许可", // 许可
                "许可链接", // 许可连接
                new ArrayList<>()// 扩展
        );
    }

    //Swagger2实例Bean是Docket,所以通过配置Docket实例来配置Swaggger2。
    @Bean
    public Docket docket(Environment environment) {
        //设置要显示swagger的环境
        Profiles of = Profiles.of("dev");
        //判断当前是否处于该环境
        boolean flag = environment.acceptsProfiles(of);
        return new Docket(documentationType.SWAGGER_2)   // 返回默认配置,必须是documentationType.SWAGGER_2
                .apiInfo(apiInfo())  // 加载自定义api的一些数据
                .groupName("默认分组")  // 如果添加多个分组,则仿写多个本方法即可,例如方法docket1
                .enable(flag)  // 启用swagger
                .select() // 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.project.controller"))   //  配置扫描的包
                .build();
    }
     右上角分类,相当于一个新的页面,
    //@Bean
    //public Docket docket1(){
    //    return new Docket(documentationType.SWAGGER_2).groupName("group1");
    //}
}

这时候其实一个最基本的swagger以及完成

6,mybatisPlus配置

这里使用mybatisPlus ,里面包含mybatis

pom.xml


    com.baomidou
    mybatis-plus-boot-starter
    3.4.3

    
        
            src/main/java
            
                **
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

完成

测试

UserMapper

package com.mall.mapper;
import com.mall.beans.Users;
import java.util.List;
public interface UserMapper  extends baseMapper {
    List all();

}

userMapper.xml




    

测试类

@SpringBootTest(classes = MallProjectApplication.class)
class MallProjectApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void test() {
        val all = userMapper.all();
        System.out.println(all); // 正常打印,说明mybaits成功

        //  分页
        Page usersPage = new Page<>(2,3);
        Page usersPage1 = userMapper.selectPage(usersPage, null);
        usersPage1.getRecords().forEach(v -> System.out.println("33[1;34m" + v + "33[1;34m n"));


    }

}

这里有一点需要特别注意,打印mapper中接口方法和普通的service这些是不一样的,区别在与顶部:,在自动生成的测试类中

@SpringBootTest
class MallProjectApplicationTests {

这种只能测试@service这些,而不能测试mapper接口中的方法,否则会报错
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test


解决

有两种方式

第一种
@SpringBootTest(classes = MallProjectApplication.class)
    
第二种:
@SpringBootTest
@ContextConfiguration(classes = MallProjectApplication.class)
8,mybatisPlus自动生成

pom.xml


    com.baomidou
    mybatis-plus-generator
    3.4.1


    org.apache.velocity
    velocity-engine-core
    2.0

MybatisPlueGenerator

package com.mall;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class MybatisPlueGenerator {
    public static void main(String[] args) {
        // 需要修改的值
        String author = "wei";// 作者
        String outputDir = "E:\PC\Desktop\project\03_mall_project\src\main\java"; //代码生成位置的绝对路径
        String url = "jdbc:mysql://localhost:3306/project_table?useSSL=false&useUnicode=true&characterEncoding=utf-8";
        String username = "root";  // 数据库账户
        String password = "root";  // 数据库密码
        String tablePrefix = "project_";//数据库表前缀
        //String includeTable = "category" ; //生成的表
        String[] includeTable = {"orders", "order_item"};// 同时生成多个表
        String parent = "com.mall";父包


        //1. 全局配置
        GlobalConfig config = new GlobalConfig();
        config.setActiveRecord(false)
                .setAuthor(author) // 作者
                .setOutputDir(outputDir) //代码生成位置的绝对路径
                .setFileOverride(true)  // 文件覆盖
                .setIdType(IdType.AUTO) // 主键策略
                .setServiceName("%sService")  // 设置生成的service接口的名字的首字母是否为I
                .setbaseResultMap(true) // 是否生成baseResultMap
                .setbaseColumnList(true); // 是否生成baseColumnList

        //2. 数据源配置
        DataSourceConfig dsConfig = new DataSourceConfig();
        dsConfig.setDbType(DbType.MYSQL)  // 设置数据库类型
                .setDriverName("com.mysql.jdbc.Driver")
                .setUrl(url)
                .setUsername(username)
                .setPassword(password);

        //3. 策略配置
        StrategyConfig stConfig = new StrategyConfig();
        stConfig.setCapitalMode(true) //全局大写命名
                .setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
                .setTablePrefix(tablePrefix) //数据库表前缀
                .setInclude(includeTable);  //生成的表

        //4. 包名策略配置
        PackageConfig pkConfig = new PackageConfig();
        pkConfig.setParent(parent) //父包
                .setMapper("mapper")
                .setService("service")
                .setController("controller")
                .setEntity("beans")
                .setXml("mapper");

        //5. 整合配置
        AutoGenerator ag = new AutoGenerator();

        ag.setGlobalConfig(config)
                .setDataSource(dsConfig)
                .setStrategy(stConfig)
                .setPackageInfo(pkConfig);

        //6. 执行
        ag.execute();
    }
}
8,打印sql语句

注意

# 
# 设置日志级别,后面跟生效的区域,比如root表示整个项目,也可以设置为某个包下,也可以具体到某个类名(日志级别的值不区分大小写)
logging:
  level:
    com:
      project:
        mapper: debug

#logging:
#  level:
#    com: debug

#  logging.level.com.qfedu.mapper=DEBUG
9,pageHelper 分页

pom.xml


    com.github.pagehelper
    pagehelper-spring-boot-starter
    1.2.13

测试

// 分页插件
PageHelper.startPage(2,3);
List all = userMapper.all();//紧跟着的第一个select方法会被分页
PageInfo pageInfo = new PageInfo<>(all);
System.out.println("===============");
System.out.println("总记录数:" + pageInfo.getTotal());
System.out.println("当前页:" + pageInfo.getPageNum());
System.out.println("总页数:" + pageInfo.getPages());
System.out.println("上一页:" + pageInfo.getPrePage());
System.out.println("下一页:" + pageInfo.getNextPage());
System.out.println("是否是首页:" + pageInfo.isIsFirstPage());
System.out.println("是否是尾页:" + pageInfo.isIsLastPage());
System.out.println("33[1;34m" + pageInfo + "33[1;34m n");
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/434170.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号