SpringBoot 小白--1(新建項目,多環(huán)境、swagger配置,MP代碼生成器)
標(biāo)簽:
SpringBoot
1. 新建项目
2. 多环境配置
<build>
<!--打包的时候,删除其它环境的配置文件-->
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<!--先排除application开头的配置文件-->
<exclude>application*.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<!--filtering 需要设置为 true,这样在include的时候,才会把
配置文件中的@env@ 这个maven`变量`替换成当前环境的对应值 -->
<filtering>true</filtering>
<includes>
<!--引入所需环境的配置文件-->
<include>application.properties</include>
<include>application-${env}.properties</include>
</includes>
</resource>
</resources>
</build>
<!--maven 多环境配置-->
<profiles>
<profile>
<id>dev</id>
<activation>
<!-- activeByDefault 为 true 表示,默认激活 id为dev 的profile-->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!--这个节点的值可以在maven的其他地方引用,可以简单理解为定义了一个叫env的变量-->
<env>dev</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>3. 集成Swagger3
pom.xml 中添加
<!-- swagger3 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
properties 中添加
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
配置Swagger
@Configuration
public class SwaggerConfig {
/**
* 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
*/
private Boolean enable = true;
/**
* 项目应用名
*/
private String applicationName = "项目名称";
/**
* 项目版本信息
*/
private String applicationVersion = "1.0.0";
/**
* 项目描述信息
*/
private String applicationDescription = "不入众,不讲理,莫劝人";
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.enable(enable)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(applicationName)
.description(applicationDescription)
.version(applicationVersion)
.build();
}
}访问地址:http://localhost:****/swagger-ui/index.html
4. MyBatis-PLUS 代码自动生成
pom文件中添加依赖:
<!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <!-- mybatis-plus-generator --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> <scope>test</scope> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
mybatis-plus官网代码生成(旧)
package com.yangxz;
import com.baomidou.mybatisplus.annotation.FieldFill;
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.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.platform.commons.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
private static final String DB_URL="jdbc:mysql://localhost:端口号/数据库?useUnicode=true&useSSL=false&characterEncoding=utf8&allowPublicKeyRetrieval=true";
private static final String DB_DRIVER_NAME="com.mysql.cj.jdbc.Driver";
private static final String DB_USERNAME="账号";
private static final String DB_PASSWORD="密码";
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("com.yangxz");
mpg.setPackageInfo(pc);
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir") + "/" + pc.getModuleName();
System.out.println(projectPath);
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("yangxz");
gc.setOpen(false);
gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DB_URL);
dsc.setDriverName(DB_DRIVER_NAME);
dsc.setUsername(DB_USERNAME);
dsc.setPassword(DB_PASSWORD);
mpg.setDataSource(dsc);
// 自定义配置
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/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
return true;
}
});
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);
if (scanner("是否集成基类?").equalsIgnoreCase("y")) {
/*设置实体类父类*/
strategy.setSuperEntityClass("com.yangxz.system.entity.BaseEntity");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("create_time", "create_account_id", "modified_time", "modified_account_id", "deleted");
}
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
/*设置表名前缀*/
// strategy.setTablePrefix(pc.getModuleName() + "_");
strategy.setTablePrefix("t_");
/*设置逻辑删除字段*/
strategy.setLogicDeleteFieldName("deleted");
/*设置自动填充*/
ArrayList<TableFill> autoFills = new ArrayList<>();
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill createAccountId = new TableFill("create_account_id", FieldFill.INSERT);
TableFill modifiedTime = new TableFill("modified_time", FieldFill.UPDATE);
TableFill modifiedAccountId = new TableFill("modified_account_id", FieldFill.UPDATE);
autoFills.add(createTime);
autoFills.add(createAccountId);
autoFills.add(modifiedTime);
autoFills.add(modifiedAccountId);
strategy.setTableFillList(autoFills);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}运行Code Generator.java 中的main()
5. 测试
1)properties文件中配置数据库连接
# 连接数据库 spring.datasource.url=jdbc:mysql://localhost:端口/数据库?useUnicode=true&useSSL=false&characterEncoding=utf8&allowPublicKeyRetrieval=true spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=账号 spring.datasource.password=密码
2)启动类添加注解
@MapperScan(basePackages = {"com.yangxz.mapper"})3)UserController文件中添加测试接口,和swagger注解
package com.yangxz.controller;
import com.yangxz.entity.User;
import com.yangxz.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author yangxz
* @since 2022-06-30
*/
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@ApiOperation("用户列表")
@GetMapping("/list")
public List<User> list(){
return userService.list();
}
}浏览器访问swagger
點擊查看更多內(nèi)容
為 TA 點贊
評論
評論
共同學(xué)習(xí),寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦






