Springboot 各种常用配置


这里记录分享平时配置 springboot 的一些常用配置,有哪些地方错误的请大家改正 😄


项目结构参考
在这里插入图片描述

数据库配置

常用 sql

id          int auto_increment primary key comment '自增主键' ,
create_time bigint        not null comment '创建时间',
update_time bigint        not null comment '更新时间',
version     int default 0 not null comment '乐观锁',
deleted     int default 0 not null comment '逻辑删除',

数据源

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/funny_db?useSSL=false&charactorEncoding=utf8&serverTimezone=UTC
    username: root
    password: enncymysql
    driver-class-name: com.mysql.cj.jdbc.Driver

spring 配置

@Bean
@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource() {
	return new DruidDataSource();
}

druid 依赖

<dependency>
    <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
	<version>1.2.6</version>
</dependency>

基础配置

统一错误处理

https://blog.csdn.net/qq_31254489/article/details/119772129

统一响应信息处理

https://blog.csdn.net/qq_31254489/article/details/119772338

Swagger 配置

记得使用 @EnableOpenApi 注解

@Configuration
@EnableOpenApi
public class GlobalConfig  {
    @Bean
    public Docket createRestApi() {

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("SpringBoot-Swagger3")
                .description("author : enncy")
                .license("Apache-2.0")
                .version("0.0.1")
                .build();

        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                //创建
                .build();
    }
}

Spring security 配置

@Configuration
@EnableOpenApi
@EnableWebSecurity
public class GlobalConfig  extends WebSecurityConfigurerAdapter {
   @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll();
    }
}

抽象业务配置

实体类的父类

@Data
@ApiModel(value = "基础实体对象", description = "基础实体对象")
public class BaseEntity {

    @JSONField(serialize = false)
    @ApiModelProperty(value = "自增主键", hidden = true)
    @TableId(value = "id", type = IdType.AUTO)
    public Integer id;


    @JSONField(serialize = false)
    @ApiModelProperty(value = "乐观锁", hidden = true)
    @Version
    public Integer version;

    @JSONField(serialize = false)
    @ApiModelProperty(value = "逻辑删除", hidden = true)
    @TableLogic
    public Integer deleted;

    @ApiModelProperty(value = "插入时间", hidden = true)
    @TableField(fill = FieldFill.INSERT)
    public Long createTime;

    @ApiModelProperty(value = "更新时间", hidden = true)
    @TableField(fill = FieldFill.INSERT_UPDATE)
    public Long updateTime;
}

控制器父类

子类控制器继承,并且传入指定的泛型,即可实现下面全部的接口

public class ServiceController<T extends BaseEntity> {

    protected IService<T> service;

    public ServiceController(IService<T> service) {
        this.service = service;
    }

    @ApiOperation("根据id查询实体")
    @GetMapping("/get/one")
    public T selectById(@RequestParam("id") int id){
        return service.getById(id);
    }

    @ApiOperation("获取全部信息")
    @GetMapping("/get/all")
    public List<T> selectAll(){
        return service.list();
    }

    @ApiOperation("根据数量查询")
    @GetMapping("/get/page")
    public List<T> selectPage(@RequestParam("current") int current, @RequestParam("size") int size){
        return service.page(new Page<>(current,size)).getRecords();
    }

    @ApiOperation("保存信息")
    @PostMapping("/insert")
    public boolean save(@RequestBody T target){
        return service.save(target);
    }

    @ApiOperation("根据id更新")
    @PostMapping("/update")
    public boolean updateById(@RequestBody  BaseDto<T> dto){
        dto.target.setId(dto.getId());
        return service.updateById(dto.target);
    }

    @ApiOperation("根据id删除")
    @GetMapping("/delete")
    public boolean removeById(@RequestParam("id") int id){
        return service.removeById(id);
    }

    @ApiOperation("查询数量")
    @GetMapping("/count")
    public int count(){
        return service.count();
    }
}

mybatis plus 配置

分页器和乐观锁插件

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 最新版 mybatis 分页器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

自动填充

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "createTime", Long.class, System.currentTimeMillis());
        this.strictUpdateFill(metaObject, "updateTime", Long.class,  System.currentTimeMillis());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 起始版本 3.3.0(推荐)
        this.strictUpdateFill(metaObject, "updateTime", Long.class,  System.currentTimeMillis());
    }
}

代码生成器

/**
 * 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
 * <br/>Created in 10:45 2021/8/16
 *
 * @author: enncy
 */

@SpringBootTest
public class MyCodeGenerator {

    @Autowired
    DruidDataSource dataSource;

    // 作者名
    private static final String author = "enncy";
    // 模块名
    private static final String module = "test";
    // 包名
    private static final String packageName = "cn.enncy";
    // 要生成的表名
    private static final String[] tableNames = {"user"};

    @Test
    public  void generate() {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆盖
        gc.setServiceName("%sService"); // 去掉 Service 的I前缀
        gc.setIdType(IdType.AUTO);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);// 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dataSource.getUrl());
        dsc.setDriverName(dataSource.getDriverClassName());
        dsc.setUsername(dataSource.getUsername());
        dsc.setPassword(dataSource.getPassword());
        mpg.setDataSource(dsc);


        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(module);
        pc.setParent(packageName);
        mpg.setPackageInfo(pc);

        // 自动填充配置

        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude(tableNames)
                .setNaming(NamingStrategy.underline_to_camel) // 下划线转驼峰
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setEntityLombokModel(true)     // 开启lombok
                .setLogicDeleteFieldName("deleted") // 逻辑删除
                .setSuperEntityClass(BaseEntity.class)  // 实体父类
                .setSuperControllerClass(ServiceController.class)  // 控制器父类
                .setRestControllerStyle(true)   // 设置 restful 风格
                .setTableFillList(Arrays.asList(createTime, updateTime)) // 自动填充
                .setVersionFieldName("version");    // 乐观锁

        mpg.setStrategy(strategy);
        mpg.execute();
    }

}

常用Maven仓库

        <!--热部署-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


        <!--德鲁伊连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

        <!--mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.1</version>
        </dependency>
        <!--mybatis 代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--velocity 模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.20</version>
        </dependency>

        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值