iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >一个完整的springboot项目所需要导入的依赖合集(方便查找)
  • 750
分享到

一个完整的springboot项目所需要导入的依赖合集(方便查找)

springbootjavaspring 2023-09-05 16:09:53 750人浏览 八月长安
摘要

一、SpringBoot启动类依赖: org.springframework.bootspring-boot-starter 二、springboot测试类依赖: org.springframework.bootspring-boot-st

一、SpringBoot启动类依赖:

org.springframework.bootspring-boot-starter

二、springboot测试类依赖:

org.springframework.bootspring-boot-starter-test

三、mybatis-plus依赖:

com.baomidoumybatis-plus-boot-starter3.4.0

四、lombok依赖(用来简化对类的操作包括:set、get以及构造函数等,只需要 一个注解)

org.projectlomboklombok

导入lombok依赖后还需要进行一步操作,下载lombok插件,方法:点击File—>Setting—>Plugins

然后再搜索框搜索Lombok,安装插件即可。

五、Mysql连接所需要的依赖:

mysqlmysql-connector-java

导入了mysql依赖后需要连接数据库,在application.yaml配置文件中配置连入数据库的参数,url:跟自己数据库的地址,我的数据库名字为mybats-plus,driver后面不变,username和passWord填上自己数据库的名字和密码即可连接。

spring:  datasource:    url: jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8    driver-class-name: com.mysql.cj.jdbc.Driver    username: root    password: huyannan*****

六、配置日志,查看sql输出日志(在application.yaml配置文件中配置)

mybatis-plus:  configuration:    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

七、 项目启动报错“javax.xml.bind.DatatypeConverter(jdk9以上版本)

这是由于java版本过高,之前java 8及以前的版本是默认包含jaxb-api包的,但是升级后的版本就需要手动来导入这个包了。所以找到pom.xml文件,然后在里边添加如下依赖

javax.xml.bindjaxb-api2.3.0com.sun.xml.bindjaxb-impl2.3.0com.sun.xml.bindjaxb-core2.3.0javax.activationactivation1.1.1

八、Redis依赖:

                    org.springframework.boot            spring-boot-starter-data-redis        

九、fastJSON依赖 :可以将 Java 对象转换为 jsON 格式,当然它也可以将 JSON 字符串转换为 Java 对象

                    com.alibaba            fastjson            1.2.33        

十、Jwt依赖

                    io.jsonWEBtoken            jjwt            0.9.1        

十一、打包跳过测试

                            org.apache.Maven.plugins                maven-surefire-plugin                2.5                                    true                            

细节配置

设置主键自动增长:

        1、需要在创建数据表的时候设置主键自增。

        2、实体字段中配置@TableId(value = "id",type = IdType.AUTO)

@Data@AllArgsConstructor@NoArgsConstructorpublic class User {    @TableId(value = "id",type = IdType.AUTO)    private Long Id;    private String Name;    private Integer Age;    private String Email;}

添加自动填充功能: 

在实体类里面对需要自动填充的属性字段添加注解。

@Data@AllArgsConstructor@NoArgsConstructorpublic class User {    //@TableId(value = "id",type = IdType.AUTO)    //可以不用设置字段自动增长,mybatis-plus自带雪花算法    private Long id;    private String name;    private Integer age;    private String email;    @TableField(fill = FieldFill.INSERT)    private Date createTime;    @TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;}

自定义实现类 MyMetaObjectHandler,实现MetaObjectHandler接口,实现接口里面的方法

package com.hu.mybatisplus01.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import org.apache.ibatis.reflection.MetaObject;import java.util.Date;@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {        @Override    public void insertFill(MetaObject metaObject) {        this.setFieldValByName("createTime",new Date(),metaObject);        this.setFieldValByName("updateTime", new Date(), metaObject);    }        @Override    public void updateFill(MetaObject metaObject) {        this.setFieldValByName("updateTime",new Date(),metaObject);    }}

添加乐观锁功能(防止丢失更新,一般只有在并发操作下发生): 

在数据库中添加version字段。

在实体类中添加version字段并在该字段上添加@Version注解。

public class User {    //@TableId(value = "id",type = IdType.AUTO)    //可以不用设置字段自动增长,mybatis-plus自带雪花算法    private Long id;    private String name;    private Integer age;    private String email;    @TableField(fill = FieldFill.INSERT)    private Date createTime;    @TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;    @Version    private Integer version;}

配置乐观插件,创建一个config配置包,在包下新建一个MybatisPlusConfig配置类。

package com.hu.mybatisplus01.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration@MapperScan("com.hu.mybatisplus01.mapper")public class MybatisPlusConfig {        @Bean    public MybatisPlusInterceptor mybatisPlusInterceptor() {        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());        return mybatisPlusInterceptor;    }}

 4、为了方便version字段值的插入,可以设置自动填充,方法同createTime字段设置类似,在version字段上添加@TableField(fill = FieldFill.INSERT)注解,然后在类 MyMetaObjectHandler中配置填充条件。 

配置分页查询功能:

        在MybatisPlusConfig配置类中添加分页插件,这是新版的,因为从MyBatis-Plus 3.4.0开始,不再使用旧版本的PaginationInterceptor ,而是使用MybatisPlusInterceptor

public class MybatisPlusConfig {    @Bean    public MybatisPlusInterceptor mybatisPlusInterceptor() {        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();        //乐观锁插件        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());        //添加分页插件        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));        return mybatisPlusInterceptor;    }}

配置逻辑删除插件: 

在数据库中添加deleted字段。字段属性为boolean。

在实体类中添加deleted字段并加上@TableLogic 和@TableField(fill = FieldFill.INSERT)注解。

在application.yaml配置文件中配置逻辑删除默认值。

mybatis-plus:  global-config:    db-config:      logic-delete-value: 1 # 逻辑已删除值(默认为 1)      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

代码生成器使用:

添加pom依赖

                    org.apache.velocity            velocity-engine-core            2.0                            com.baomidou            mybatis-plus-generator            3.4.0        

mybatis3.5.1以下版本使用

package com.hu.demo;import com.baomidou.mybatisplus.annotation.DbType;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.generator.config.GlobalConfig;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.rules.DateType;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import org.junit.Test;// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中public class CodeGenerator {    @Test    public void run() {        // 代码生成器        AutoGenerator mpg = new AutoGenerator();        // 全局配置        GlobalConfig GC = new GlobalConfig();        String projectPath = System.getProperty("user.dir");        gc.setOutputDir(projectPath + "/src/main/java");        gc.setAuthor("胡雁南");        gc.setOpen(false);        gc.setServiceName("%sService");//去掉Service接口的首字母I        gc.setIdType(IdType.ID_WORKER_STR);        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型        gc.setswagger2(true);// 实体属性 Swagger2 注解        mpg.setGlobalConfig(gc);        // 数据源配置(改成自己的数据库 )        DataSourceConfig dsc = new DataSourceConfig();        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");        // dsc.setSchemaName("public");        dsc.setDriverName("com.mysql.cj.jdbc.Driver");        dsc.setUsername("root");        dsc.setPassword("huyannan");        dsc.setDbType(DbType.MYSQL);        mpg.setDataSource(dsc);        // 包配置        PackageConfig pc = new PackageConfig();        pc.setParent("com.hu");//com.hu        pc.setModuleName("eduservice");//模块名;;com.hu.eduservice        //包com.hu.eduservice.controller        pc.setController("controller");        pc.setEntity("entity");        pc.setService("service");        pc.setMapper("mapper");        mpg.setPackageInfo(pc);        // 策略配置        StrategyConfig strategy = new StrategyConfig();        strategy.setInclude("edu_teacher");//具体表        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略        strategy.setTablePrefix(pc.getModuleName() + "_");//生成实体时去掉表前缀        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略        strategy.setEntityLombokModel(true);//Lombok模型        strategy.setRestControllerStyle(true);//restful api风格控制器        strategy.setControllerMappingHyphenStyle(true);//url中驼峰转连字符        mpg.setStrategy(strategy);        mpg.execute();//执行    }}

配置统一返回的json格式,在application.yaml配置文件中设置:

#返回json的全局时间格式spring:     jackson:    date-fORMat: yyyy-MM--dd HH:mm:ss    time-zone: GMT+8

建立统一返回结果集:

创建一个utils工具包,在包下建立ResultCode接口和R类,ResultCode接口中配置返回结果码常量,R类用来封装统一返回结果集。

ResultCode代码

package com.hu.utils;public interface ResultCode {    Integer SUCCESS=20000;//成功    Integer ERROR=20001;//失败}

R类代码

package com.hu.utils;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import java.util.HashMap;import java.util.Map;@Datapublic class R {    @ApiModelProperty(value = "是否返回成功")    private Boolean success;    @ApiModelProperty(value = "返回码")    private Integer code;    @ApiModelProperty(value = "返回消息")    private String message;    @ApiModelProperty(value = "返回数据")    private Map data = new HashMap();    private R(){}//构造方法私有化,使外部不能实例化    //成功静态方法    public static R ok(){        R r = new R();        r.setSuccess(true);        r.setCode(ResultCode.SUCCESS);        r.setMessage("成功");        return r;    }    //失败静态方法    public static R error(){        R r = new R();        r.setSuccess(false);        r.setCode(ResultCode.ERROR);        r.setMessage("失败");        return r;    }    //实现链式编程    public R success(Boolean success){        this.setSuccess(success);        return this;    }    public R message(String message){        this.setMessage(message);        return this;    }    public R code(Integer code){        this.setCode(code);        return this;    }    public R data(String key,Object value){        this.data.put(key, value);        return this;    }    public R data(Mapmap){        this.setData(map);        return this;    }}

统一异常处理:

        在handler处理包下新建一个 GlobalExceptionHandler全局异常统一处理配置类,若有异常前端不会直接提示500错误。

(1)全局异常处理。

package com.hu.handler;import com.hu.utils.R;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;@ControllerAdvicepublic class GlobalExceptionHandler {    @ResponseBody//为了能够返回数据    //指定出现什么异常执行这个方法    @ExceptionHandler(Exception.class)    public R error(Exception e){        e.printStackTrace();        return R.error().message("执行了全局异常处理");    }}

(2)特定异常

package com.hu.handler;import com.hu.utils.R;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;@ControllerAdvicepublic class GlobalExceptionHandler {        //特定异常    @ResponseBody//为了能够返回数据    @ExceptionHandler(ArithmeticException.class)    public R error(ArithmeticException e){        e.printStackTrace();        return R.error().message("执行了ArithmeticException异常处理");    }}

(3)自定义异常

第一步先创建自定义的异常类继承RuntimeException。

package com.hu.handler;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublic class CustomException extends RuntimeException{    private Integer code;//状态码    private String msg;//异常信息}

第二步在统一异常类GlobalExceptionHandler中添加规则。

package com.hu.handler;import com.hu.utils.R;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;@ControllerAdvicepublic class GlobalExceptionHandler {        //自定义异常    @ResponseBody//为了能够返回数据    @ExceptionHandler(CustomException.class)    public R error(CustomException e){        e.printStackTrace();        return R.error().code(e.getCode()).message(e.getMsg());    }}

配置阿里云的OSS云存储服务。

官方教程:

安装 (aliyun.com)https://help.aliyun.com/document_detail/32009.html博主仅仅配置了一个文件上传的功能,用来修改和保存头像的。

第一步配置maven依赖:

                    com.aliyun.oss            aliyun-sdk-oss            3.10.2        

第二步在utils工具包写创建AvatarUtils工具类

AvatarUtils工具类代码:

package com.hu.utils;import com.aliyun.oss.OSS;import com.aliyun.oss.OSSClientBuilder;import com.hu.handler.CustomException;import com.hu.utils.commonResult.ResultCode;import org.springframework.web.multipart.MultipartFile;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;public class AvatarUtils {    public static final String defaultAvatarUrl="填默认头像地址";    // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。    private static String endpoint = "";    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。    private static String accessKeyId = "";    private static String accessKeySecret = "";    // 填写Bucket名称,例如examplebucket。    private static String bucketName = "";    public static String ossUploadAvatar(MultipartFile multipartFile){        String imageUrl=null;        // 创建OSSClient实例。        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);        try {            //获取文件上传的流            InputStream inputStream = multipartFile.getInputStream();            //构建日期目录            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");            String datePath = dateFormat.format(new Date());//日期目录2022/10/10            //获取文件名            String originalFilename = multipartFile.getOriginalFilename();            //随机生成一个文件名            String filename = UUID.randomUUID().toString();            //获取文件后缀名            int i = originalFilename.lastIndexOf(".");            String substring = originalFilename.substring(i);            //判断图片是否符合要求            if (!substring.equals(".jpg")&&!substring.equals(".png"))            {                throw new CustomException(ResultCode.ERROR,"上传图片格式错误,只能是.jpg或者.png");            }            //得到的随机文件名和后缀名拼接成一个新的完整的文件名            String newFilename = filename.concat(substring);            //最后完整的文件路径            String fileUrl = datePath.concat("/").concat(newFilename);            //通过io流将文件传给阿里云的文件存储桶,生成fileUrl这样的一个文件            ossClient.putObject(bucketName, fileUrl, inputStream);            imageUrl = "Https://".concat(bucketName).concat(".").concat(endpoint).concat("/").concat(fileUrl);        }catch (Exception ce) {            ce.printStackTrace();        } finally {            if (ossClient != null) {                ossClient.shutdown();            }        }        return imageUrl;    }}

第三步、通过调用AvatarUtils类下的ossUploadAvatar方法即可获得一个路径,可以选择存在数据库中。

//MultipartFile文件上传类型封装public  Boolean uploadFileByStudent(MultipartFile multipartFile){        String imageUrl = AvatarUtils.ossUploadAvatar(multipartFile);    }

添加MD5加密工具类 ,在utils工具包下新建一个MD5工具类

package com.hu.utils;import java.security.MessageDigest;import java.security.NoSuchAlGorithmException;public class MD5Utils {    public static String encrypt(String strSrc) {        try {            char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',                    '9', 'a', 'b', 'c', 'd', 'e', 'f' };            //得到加密对象,MD5加密算法只是对字节数组进行加密计算            byte[] bytes = strSrc.getBytes();            //获取MD5加密实例            MessageDigest md = MessageDigest.getInstance("MD5");            // 使用指定的字节更新实例            md.update(bytes);            // 获得密文            bytes = md.digest();            int j = bytes.length;            char[] chars = new char[j * 2];            int k = 0;            // 把每一个byte 做一个与运算            for (int i = 0; i < bytes.length; i++) {                byte b = bytes[i];                chars[k++] = hexChars[b >>> 4 & 0xf];                chars[k++] = hexChars[b & 0xf];            }            return new String(chars);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();            throw new RuntimeException("MD5加密出错!!+" + e);        }    }    public static void main(String[] args) {        System.out.println(MD5Utils.encrypt("111111"));    }}

redis配置 :

windows下安装redis:

下载地址:Releases · microsoftarcHive/redis · GitHubhttps://github.com/MicrosoftArchive/redis/releases

下载后是个压缩文件,对其解压 

解压后可以看到服务、客户端等,选择服务redis-server.exe双击开启。再选择客户端redis-cli.exe双击启动,在客户端输入ping,返回PONG则说明连接成功了

redis整合到项目中

引入redis依赖:

                    org.springframework.boot            spring-boot-starter-data-redis        

配置连接的application.yml文件: 

spring:  redis:    host: 127.0.0.1    port: 6379

测试连接:写个测试方法来进行最基本的连接测试!

@Autowired(required = false)    private RedisTemplate redisTemplate;    @Test    void getName(){        redisTemplate.opsForValue().set("name","huyan!");        System.out.println(redisTemplate.opsForValue().get("name"));    }

运行效果如下!证明Redis连接成功!并且加数据获取数据也成功了! 

权限模块固定写法 :

新建五张表:菜单表;角色表;用户表;菜单角色关系表;角色用户关系表

在maven中导入spring_security和fastjson依赖

                    org.springframework.boot            spring-boot-starter-security                                    com.alibaba            fastjson            1.2.62        

持续新中~

来源地址:https://blog.csdn.net/qq_56728342/article/details/125417615

您可能感兴趣的文档:

--结束END--

本文标题: 一个完整的springboot项目所需要导入的依赖合集(方便查找)

本文链接: https://www.lsjlt.com/news/395620.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作