首页 > 其他分享 >从零搭建SpringBoot3一,手动编写一套属于自己风格的代码生成器一键生成系统

从零搭建SpringBoot3一,手动编写一套属于自己风格的代码生成器一键生成系统

时间:2023-07-04 22:26:07浏览次数:49  
标签:代码生成 java String filePath light 一键 生成 SpringBoot3 com

简介

虽然 java 的代码生成工具有很多,可是很多时候不是自己喜欢的风格,改起来比较困难,所以我准备从零和大家一起搭建一套基于 springboot3.0 的框架,
这次就先搞定一套代码生成功能,后续再不断的完善其它

我们使用到的三方库:

  1. beelt 模版引擎,用于生成代码。官网:http://ibeetl.com
  2. mybatis-plug 官网:https://www.baomidou.com/

开始

第一步,创建一个 maven 项目,然后在 pom.xml 中引入相关依赖,用到数据库驱动,阿里的数据库连接池等

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springboot-generate</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>20</maven.compiler.source>
        <maven.compiler.target>20</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.6</version>
    </parent>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.5.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.ibeetl/beetl -->
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl-springboot-starter-jdk17</artifactId>
            <version>3.15.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

第二步,在 java 文件夹下创建个包 com.light,并在下创建启动入口 Application.java,注意不要直接在 java 下创建,代码

@MapperScan("com.light.business.*.mapper") 
@EnableBeetl //会拦截.btl文件使用Beetl语法解析
@RestController
@SpringBootApplication
public class Application {
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

第三步,去实现代码生成,思路是通过一个页面(这样可视化,看起来更直观)来展示可以生成的表,选择后调用一个接口生成到项目中所以,我们先来个html用于展示表名以及操作
我们在 resouces 下创建 templates/generate/index.btl 文件,templates是缺省目录,我们就直接用,而index.btl不用.html因为我们用模板引擎。
可以看到,很简单展示一下表名称,然后可以选择提交

<head>
    <meta charset="UTF-8">
    <title>代码自动生成器</title>
</head>
<style>
    body {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 25px;
    }
</style>
<body>
    <h1> 欢迎使用 Light 代码一键生成器 </h1>
    <div style="min-width: 450px">
        <div>
            <input type="button" style="margin-right:45px" onclick="selectReverse()" value="反选">
            <input type="button" value="提交并生成代码" onclick="document.tableForm.submit()">
        </div>
        <div style="margin-top: 12px;margin-bottom: 2px">
            <b>请选择要生成的数据表:</b>
        </div>
        <form name="tableForm" method="post" action="index">
            <% 
                for(tableName in tableNames) { 
                    println("<input type='checkbox' name='table' value='" + tableName + "'>" + tableName + "<br>");
                }
            %>
        </form>
    </div>
    <script>
        function selectReverse() {
            let tables = document.getElementsByName("table");
            for (let table of tables) {
                table.checked = !table.checked;
            }
        }
    </script>
</body>

第四步,因为上一步中需要展示表名,所以应该要一个查询表名称的方法,我们在 com.light 下创建 common.generate.service.GenerateService.java,然后添加查询表名的方法

@Autowired
private JdbcTemplate jdbcTemplate;

public List<String> getTableNames(String tableSchema) {
    String sql = "SELECT table_name as tableName FROM INFORMATION_SCHEMA.TABLES\n" +
            "WHERE table_schema = '" + tableSchema + "'";
    return jdbcTemplate.query(sql, new RowMapper<String>() {
        @Override
        public String mapRow(ResultSet resultSet, int i) throws SQLException {
            return resultSet.getString(1);
        }
    });
}

第五步,我们在 com.light 下创建common.generate.controller.GenerateController,来用于访问,如果有选择了表,就会调用生成功能

@Value("${spring.datasource.url}")
private String databaseUrl;
@Autowired
private GenerateService generateService;
//引入包的前缀
private static String comPath = "com.light.business";
//文件生成的路径
private static String[] filePath = new String[]{ System.getProperty("user.dir"), "src", "main", "java", "com", "light", "business" };

@RequestMapping(value = "/index")
public ModelAndView index(String[] table) throws IOException {
    String schema = databaseUrl.substring(databaseUrl.lastIndexOf("/") + 1, databaseUrl.indexOf("?"));

    if (table != null) {
        generateService.generation(Util.addFileSeparator(filePath), comPath, schema, Arrays.asList(table));
    }

    ModelAndView view = new ModelAndView();
    view.setViewName("/generate/index.btl");
    view.addObject("tableNames", generateService.getTableNames(schema));
    return view;
}

第六步,可以看到核心就是 servicegeneration 方法,所以在 GenerateService.java 中添加方法

public void generation(String filePath, String comPath, String schema, List<String> tableNames) throws IOException {
    //我们在 resouces下创建个 beetl-back-end 用于放模板
    ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("beetl-back-end");
    Configuration cfg = Configuration.defaultConfiguration();
    //加载模板组
    GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
    //获取表以及其字段等信息
    List<TableInfo> tableInfoList = getTableInfoList(schema, tableNames);

    System.out.println("generate start");
    for (TableInfo tableInfo: tableInfoList) {
        //生成PO...
        doPo(gt, tableInfo, comPath, filePath);
        doVo(gt, tableInfo, comPath, filePath);

        doMapperJava(gt, tableInfo, comPath, filePath);
        doMapperXml(gt, tableInfo, comPath, filePath);

        doService(gt, tableInfo, comPath, filePath);
        doController(gt, tableInfo, comPath, filePath);
    }
    System.out.println("generate over");
}

其它代码就不贴出来了,开源的,可以自己到 github 上。

当前可以生成 controller, service, mapjava, mapxml, PO, VO

思考

预留了根据注释生成对应字段的枚举功能,因为还在思考如何才合理。那么是否还可以根据数据字段信息来生成校验功能呢?或者你认为还有什么是需要生成的呢?然后我们再来继续扩展

使用

下载项目后,配置 application.yml 中的数据库连接

  1.png

启动项目后在浏览器中输入 http://localhost:8888/generate/index 即可访问代码生成入口,我们全选后点击提交

  2.png

 

然后就完成了,可以看到项目的 com.light 下创建了个 business 目录,里面就是生成的代码了,所有的功能就已经完成了

  3.png

如果添加表或修改了表,点击需要的表重新生成即可,PO、VO等会覆盖生成,具体在 com.light.common.generate.Config.java 中配置了

测试

由于我们从零开始创建的,所以还没有 swagger 等等,postman 一个一个测试太慢了,所以我们这里借助前端自动生成功能来测试

由于前端是在线生成,所以访问本地存在跨域问题,那们在本地我们先允许任何域访问,在com.light.common下创建 config.CustomCorsConfiguration.java,简单配置:

@Configuration
public class CustomCorsConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 放行哪些原始域
                .allowedOrigins("*")
                // 放行哪些请求方式
                .allowedMethods("*")
                // 放行哪些原始请求头部信息
                .allowedHeaders("*");
    }
}

重启项目

打开前端代码生成器网站:https://light2f.com 到我的项目下,点击 AI创建项目,输入数据库信息或者导入数据库结构

  4.png

如果没有配置过端口与path应该输入如下基本路径信息。
后选择或自动生成一套母版使用

  5.png

由于我们springboot框架是从零搭建的,所以还没有封装 response,所以将模版修改红框中数据为下面

  6.png

直接确定生成

  7.png

点击刚刚生成的项目点击眼睛进入预览

  8.png

我们还没有token与登录,所以直接点击右边跳过

  9.png

ok, 接口字段等已经接入,可以测试了。

  1.gif

总结

一个完成的从前到后功能已经完成了,但是实际使用中会有安全问题、权限问题等等,那么我们那一期再完善一下 token 等,或者等小伙伴提需求
一起一步一步完善后继搭建



作者:杨一一_04a3
链接:https://www.jianshu.com/p/a7ff4206dc19
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

标签:代码生成,java,String,filePath,light,一键,生成,SpringBoot3,com
From: https://www.cnblogs.com/xmsz118/p/17527167.html

相关文章

  • SpringBoot3.0从入门到项目实战:解决Web应用痛点的最新解决方案
    SpringBoot3.0从入门到项目实战:解决Web应用痛点的最新解决方案SpringBoot是当前Java领域中应用最广的框架之一,而随着SpringBoot3.0的发布,它迎来了更加全面和强大的一次升级。本文将深入浅出地介绍SpringBoot3.0的新特性,同时结合实际项目经验,分享Web应用的痛点以及解决方案,帮......
  • 一键上阿里云可采集多种设备网关BL110
    BL110是一款功能强大的PLC协议支持网关。它具有多种协议转换能力,包括ModbusRTU、ModbusTCP、DL/T645、IEC101、IEC104、BACnetIP、BACnetMS/TP等。随着物联网技术的不断发展,PLC设备之间的互联和通信变得日益重要。然而,不同的PLC设备通常采用不同的通信协议,这就给PLC系统的集成......
  • Jenkins+Docker 实现一键自动化部署项目
    Jenkins+Docker实现一键自动化部署项目!步骤齐全,少走坑路!JAVA编程Linux学习 2023-07-0108:10 发表于山东收录于合集#docker4个#Jenkins1个本文章实现最简单全面的Jenkins+docker+springboot一键自动部署项目,步骤齐全,少走坑路。环境:centos7+git(gitee)简述实现......
  • Bat批处理命令实现一键安装mysql环境
    已测试可用的版本MySQL8.0;环境:windows7/10MySQL8.0.15免安装版项目需求需要实现一个自动化MySQL配置安装及初始化数据库(初始化包括:设置用户名和密码)。批处理用来对某对象进行批量的处理,即可通过批处理让相应的软件执行自动化操作。MySQL免安装版使用步骤:1.配置环境变量2.创建MySQ......
  • lnmp下一键切换php7与8脚本
    先去/usr/local目录下,新建php7bak,php8bak两个目录,假设当下默认安装的是php7,则将php8的目录复制到php8bak目录下备用。 shell脚本如下:#!/bin/bashpath7=/usr/local/php7bakpath8=/usr/local/php8bakpid=emptyif[!-d$path7/php];thenecho'Startconvertingph......
  • OpenStack(五)使用Packstack工具一键安装OpenStack
    环境规划操作系统虚拟机配置IP地址主机名虚拟机软件OpenStack版本CentOS7.94CPU/8G内存/30G硬盘192.168.0.31openstackVMwareWorkStation17Stein准备安装从阿里源下载CentOS镜像或者:链接:https://pan.baidu.com/s/15jyPVOAHA6tafwUk863b9g?pwd=ekq5 ......
  • SpringBoot3.0最新深入浅出从入门到项目实战,突出Web应用痛点解决方案
    SpringBoot3.0最新深入浅出从入门到项目实战,突出Web应用痛点解决方案SpringBoot已经成为Java开发中最流行的框架之一,它提供了一种快速构建、易于扩展的方式,使开发人员能够更加专注于业务逻辑而不是繁琐的配置。而最新的SpringBoot3.0版本将进一步改善开发体验,并提供更多的解决方......
  • 代码生成器 CodeBuilder 3 正式版发布
    CodeBuilder是一款强大的代码生成工具,目前发布了3.0,大家可以前去下载体验官方主页。1、多种数据源基于ADO.NET的数据驱动基于Fireasy3,支持从SqlServer、MySql、Oracle、Firebird、PostgreSql、SQLite、达梦、人大金仓、神通数据库,以及Odbc、OleDb驱动。可以获取所有......
  • C# Visual Studio 一键整理实体类里的get set格式
    多人开发中,很难保证大家的审美都一样有的人喜欢下面这样,publicstringName{get;set;}有的人喜欢这样,publicstringName{get;set;}那么怎样一键让所有这些变成下面那样呢......
  • springboot3视频教程,很多可用的教学资源
    不得不说,学习SpringBoot是非常有必要的,尤其是对于Java后端开发人员来说。SpringBoot是基于SpringFramework的快速开发框架,通过自动配置和约定优于配置的原则,大大简化了Spring应用的开发和部署。它提供了丰富的功能和开箱即用的特性,可以帮助开发者快速搭建高效、可靠的企业级应用......