目录

Spring Boot 项目指南

目录

使用 gradle 作为构建工具。

使用 IDEA,选择创建新项目,选择 Spring Initializer ,然后选择依赖和填写项目相关信息即可。

目前用到的依赖:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-amqp'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-quartz'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.2'
    implementation 'org.springframework.session:spring-session-data-redis'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation 'org.springframework.amqp:spring-rabbit-test'
  	compile 'com.baomidou:mybatis-plus-boot-starter:3.3.1.tmp'  // mybatis-plus
    compile 'com.baomidou:mybatis-plus-generator:3.3.1.tmp'  // mybatis-plus-generator
    compile 'org.apache.velocity:velocity-engine-core:2.2'  // velocity
    compile 'io.springfox:springfox-swagger2:2.9.2'  // swagger2
    compile 'io.springfox:springfox-swagger-ui:2.9.2'  //swagger2-ui
}

然后需要使用公共代理库,加快依赖获取速度:

repositories {
    maven {
        url "https://maven.aliyun.com/repository/central"
    }
}

配置数据库:

user.host=192.168.122.7
spring.main.banner-mode=off
spring.data.mongodb.host=${user.host}
spring.data.mongodb.port=27017
spring.data.mongodb.database=spas

spring.redis.host=${user.host}
spring.redis.port=6379
spring.redis.password=Passw0rd!

spring.datasource.username=spas
spring.datasource.password=Passw0rd!
spring.datasource.url=jdbc:mysql://${user.host}:3306/spas?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

配置 Swagger2:

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    public ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("检察建议流程辅助办案系统")
                .description("API 接口文档")
                .version("1.0")
                .build();
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.spas.backend"))
                .paths(PathSelectors.any())
                .build();
    }
}

编写并启动代码生成器:

package com.spas.backend.util;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;

public class CodeGenerator {

  /**
  * 命令行提示.
  * @param tip 提示
  * @return null
  */

  public static String scanner(String tip) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("请输入" + tip + ":");
    if (scanner.hasNext()) {
      String ipt = scanner.next();
      if (StringUtils.isNotEmpty(ipt)) {
        return ipt;
      }
      throw new MybatisPlusException("请输入正确的" + tip + "!");
    }
    return null;
  }

  /**
   * main 方法生成代码.
   * @param args 命令行变量
   */
  public static void main(String[] args) {
    // 代码生成器
    final AutoGenerator mpg = new AutoGenerator();

    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("Yuhan Liu");
    gc.setOpen(false);
    gc.setSwagger2(true);  // 实体属性 Swagger2 注解
    gc.setServiceName("%sService");  // 改变 Service 名称
    mpg.setGlobalConfig(gc);

    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://192.168.122.7:3306/"
        + "spas?useUnicode=true&useSSL=false&characterEncoding=utf8");
    // dsc.setSchemaName("public");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("spas");
    dsc.setPassword("Passw0rd!");
    mpg.setDataSource(dsc);

    // 包配置
    PackageConfig pc = new PackageConfig();
    // pc.setModuleName(scanner("模块名"));
    pc.setParent("com.spas.backend");
    mpg.setPackageInfo(pc);
    // 自定义配置
    InjectionConfig cfg = new InjectionConfig() {
        @Override
        public void initMap() {
            // to do nothing
        }
    };

    // 如果模板引擎是 freemarker
    // String templatePath = "/templates/mapper.xml.ftl";
    // 如果模板引擎是 velocity
    String templatePath = "/templates/mapper.xml.vm";

    // 自定义输出配置
    List<FileOutConfig> focList = new ArrayList<>();
    // 自定义配置会被优先输出
    focList.add(new FileOutConfig(templatePath) {

        @Override
        public String outputFile(TableInfo tableInfo) {
            // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
            return projectPath + "/src/main/resources/mapping/" // + pc.getModuleName() + "/"
                + tableInfo.getEntityName() + "Mapping" + StringPool.DOT_XML;
        }
    });
    /*
    cfg.setFileCreate(new IFileCreate() {
        @Override
        public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
            // 判断自定义文件夹是否需要创建
            checkDir("调用默认方法创建的目录");
            return false;
        }
    });
    */
    cfg.setFileOutConfigList(focList);
    mpg.setCfg(cfg);

    // 配置模板
    TemplateConfig templateConfig = new TemplateConfig();

    // 配置自定义输出模板
    //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
    // templateConfig.setEntity("templates/entity2.java");
    // templateConfig.setService();
    // templateConfig.setController();

    templateConfig.setXml(null);
    mpg.setTemplate(templateConfig);

    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
    strategy.setEntityLombokModel(true);
    strategy.setRestControllerStyle(true);
    // 公共父类
    // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
    // 写于父类中的公共字段
    // strategy.setSuperEntityColumns("id");
    // strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    String[] myTableNames = {"case","comment","department","menu","office","operation","plan","plan_report","report","role","role_menu","role_operation","suggestion","user"};
    strategy.setInclude(myTableNames);
    strategy.setControllerMappingHyphenStyle(true);
    // strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    // mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
  }

}

在代码生成器生成的文件中,添加应有的信息

  • MyBatis Plus 注解