基于SpringBoot2.1.x框架的一些经常使用开发介绍

1、创建初始的工程

可使用官网https://start.spring.io/,或者 idea来新建springboot工程。前提条件是安装好jdk8和maven3.2以上版本。使用的idea也要作好jdk、maven、utf-8编码格式设置。html

在pom.xml文件,能够修改springboot的版本号。从新导入maven便可。java

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

 

 

 

 1.1 先不链接数据库,启动project。

  若是报数据库的错,给注释 @SpringBootApplication 添加参数。mysql

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

 

 1.2 一般是为了开发web项目, 因此添加web的依赖。

  由于已经指定了parent是2.1.6.RELEASE版本的spring-boot-starter-parent,这里web的版本不须要指定。linux

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

 

  添加一个用于测试的controller。访问 http://localhost:8010/user/test , 正常便可。
nginx

@Controller @RequestMapping("user") public class UserController { @RequestMapping("test") @ResponseBody public String test(){ return "test"; } }

1.3 辅助工具

        <!-- 热部署 devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

 

 

2、链接数据库

2.1 数据库使用mysql5.7,mybatis3做为ORM。

  mysql5.7在win和linux下的安装操做,参考个人其它两篇博客:“记一次linux下安装mysql5.7”,“在win下,安装MySQL5.7”。web

  再介绍docker安装mysql5.7的作法。拉取iamge,docker pull centos/mysql-57-centos7。redis

[root@master ~]# docker images 
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
nginx                     latest              a1523e859360        2 weeks ago         127MB
mongo                     latest              bcef5fd2979d        2 weeks ago         386MB
centos/mysql-57-centos7   latest              f83a2938370c        5 months ago        452MB
redis                     3.2                 87856cc39862        17 months ago       76MB

 

  启动mysql容器。我没有使用数据卷 -v,挂载到宿主机。spring

docker run -di -p 3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=123456 centos/mysql-57-centos7

 

  mysql数据库,建新库使用utf8字符集,排序建议使用utf8_unicode_xx。sql

  创建一张user测试表。docker

CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `telphone` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `password` varchar(200) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `nick_name` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `gender` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `telphone_unique_index` (`telphone`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

2.2 添加数据库链接和mybatis3的依赖,以及逆向工程。

        <!-- 数据库mysql和mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

 

  删除启动类上的 exclude = DataSourceAutoConfiguration.class 这个参数。

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
name: dianpingdb
url: jdbc:mysql://master:3306/dbname?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:com/xxx/mapper/*.xml
type-aliases-package: com.xxx.pojo.entity

# 为了打印sql
logging:
level:
com.xxx.mapper: debug

debug: true

  

  使用mybatis 的逆向工程, 参考 http://mybatis.org/generator/ 。第一步,使用插件。

    <build>
        <!-- mybatis 逆向工程 -->
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.5</version>
                    <dependencies>
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.5</version>
                        </dependency>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>5.1.47</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>mybatis generator</id>
                            <phase>package</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <!--容许移动生成的文件-->
                        <verbose>true</verbose>
                        <!--容许自动覆盖文件-->
                        <overwrite>true</overwrite>
                        <configurationFile> src/main/resources/mybatis-generator.xml </configurationFile>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

  第二步,添加文件 mybatis-generator.xml

<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="simple" targetRuntime="MyBatis3Simple">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://master:3306/dbname" userId="root" password="123456"/>
        <!-- 实体类 -->
        <javaModelGenerator targetPackage="com.xxx.pojo.entity" targetProject="src/main/java"/>

        <!-- xml的mapper文件-->
        <sqlMapGenerator targetPackage="com.xxx.mapper" targetProject="src/main/resources"/>
        <!-- interface 文件 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.mapper" targetProject="src/main/java"/>

        <table tableName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        </table>

    </context>
</generatorConfiguration>

  第三步,maven启动。

  mvn mybatis-generator:generate

 2.3 读取数据库记录测试

    @GetMapping("get") @ResponseBody public User getUserById(@RequestParam Integer id){ return userService.getUserById(id); }
public interface UserService { User getUserById(Integer id); }
@Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public User getUserById(Integer id) { return userMapper.selectByPrimaryKey(id); } }

 

 2.4 引入mybatis-plus

除了mybatis以外,还有集成度更高的 mybatis plus。

好比给定一个 User实体类。

添加依赖

      <dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus-boot-starter</artifactId>
          <version>3.2.0</version>
      </dependency>    

 

对应的 mapper接口

@Repository public interface UserMapper extends BaseMapper<User> { }

 

以及service

public interface UserService extends IService<User> { }

 

@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { }

 

 IService 和 ServiceImpl 都是 mybatis-plus提供的。

在controller里调用

@Autowired
UserService userService;
User user = userService.getById(1L);

 

3、规定通用返回的格式和全局异常处理。

3.1 通用返回

import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Data; @Data @Builder public class Result { private int code; private String msg; @JsonInclude(JsonInclude.Include.NON_NULL) private Object data;    // 不要返回null值。

    public static Result success(Object data) { return Result.builder() .data(data).msg("success").code(200) .build(); } public static Result create(ErrorCode errorCode){ return Result.builder() .msg(errorCode.msg).code(errorCode.code) .build(); } }

新建错误码枚举类

public enum ErrorCode { OBJECT_NOT_FOUNT(10001, "请求对象不存在"), UNKNOWN_ERROR(10002, "未知错误"), NO_HANDLER_FOUND(10003, "找不到页面,有多是提交的路径或参数不对。"), PARAMETER_ERROR(10004, "请求的参数不对"), ; public int code; public String msg; ErrorCode(int code, String msg) { this.code = code; this.msg = msg; } }

 测试返回内容

    @GetMapping("get") @ResponseBody public Result getUserById(@RequestParam Integer id) throws GlobalException { User userById = userService.getUserById(id); if(userById==null){ // 统一返回错误码
            return Result.create(ErrorCode.OBJECT_NOT_FOUNT); } return Result.success(userById); }

3.2 全局异常处理

 在错误码的基础上,新建自定义异常类。

@Data public class GlobalException extends Exception{ private ErrorCode errorCode; public GlobalException(ErrorCode errorCode) { super(); this.errorCode = errorCode; } }

 

 新建异常处理handler的类。

@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) Result handlerException(HttpServletRequest request, HttpServletResponse response, Exception ex){ if(ex instanceof GlobalException){ // 自定义的异常类
            GlobalException exception = (GlobalException) ex; return Result.create(exception.getErrorCode()); }else if(ex instanceof NoHandlerFoundException){ // 404 没找处处理页面
            return Result.create(ErrorCode.NO_HANDLER_FOUND); }else if(ex instanceof MissingServletRequestParameterException){ // 提交的参数不对
            return Result.create(ErrorCode.PARAMETER_ERROR); }else { return Result.create(ErrorCode.UNKNOWN_ERROR); } } }

 

为了阻止默认的404错误页面,要添加配置。

spring:
#出现错误时, 直接抛出异常,如下2个配置都要有。

mvc: throw-exception-if-no-handler-found: true resources: add-mappings: false

参考 https://www.jianshu.com/p/36505ac4d32a

测试controller

 

    @GetMapping("get")
    @ResponseBody
    public Result getUserById(@RequestParam Integer id) throws GlobalException {
        User userById = userService.getUserById(id);
        if(userById==null){
            // 统一返回错误码,固然也能够。
            // return Result.create(ErrorCode.OBJECT_NOT_FOUNT);
            // 这里尝试抛出异常,再统一作自定义的全局异常处理。
            throw new GlobalException(ErrorCode.OBJECT_NOT_FOUNT);
        }
        return Result.success(userById);
    }
相关文章
相关标签/搜索