Spring Boot基础项目

Spring Boot基础项目

新建统一Spring Boot的父工程

新建一个通用的父工程,为pom工程,继承于spring-boot-starter-parent,可以维护一些自定义的版本、插件等信息等。

然后可以再在下级新建子项目的pom或者jar工程。

下面以简单的数据库访问工程为例,会使用到lombok、mybatis-plus,需要引入相关的版本配置。

详细源码地址:https://github.com/fugary/meng-study/tree/master/simple-boot-parent

父工程POM

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mengstudy</groupId>
    <artifactId>simple-boot-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <!--spring-boot数据库访问demo,后面生成子项目的时候添加-->
        <module>simple-boot-demo</module>
        <!--spring-boot事务相关demo,后面使用到再添加-->
        <module>simple-boot-transaction-parent</module>
    </modules>
    <name>simple-boot-parent</name>
    <description>Simple parent project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository 从maven仓库查找父工程-->
    </parent>
    <properties>
        <java.version>1.8</java.version>
        <mybatis-spring-boot-starter.version>2.1.2</mybatis-spring-boot-starter.version>
        <mybatis-plus-boot-starter.version>3.3.1</mybatis-plus-boot-starter.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis-spring-boot-starter.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis-plus-boot-starter.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

继承Spring Boot项目

通常Spring Boot项目需要继承spring-boot-starter-parent项目,里面已经定义很多常用的依赖库的版本,由于spring-boot-starter-parent作为父级项目是在外部仓库,因此需要配置relativePath。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository 从maven仓库查找父工程-->
</parent>

关于relativePath说明:

  1. relativePath是指定父工程的地址,默认为../,即上级目录。
  2. 外部项目作为父工程,配置为空节点<relativePath/>
  3. 如果子工程并不在父工程中,需要在子工程中指定相对路径,如:<relativePath>../path-to-parent</relativePath>

新建子级工程

一般最外层的父工程可以管理一些版本,插件等,可以在此基础上新建spring boot jar工程了,当然子项目内部的工程可以有自己的父级工程,自定义一些通用的配置。

新建子工程

可以用idea向导生成子工程,按照向导新建即可,但是有时候网络有问题,可能会失败。子项目名称:simple-boot-demo,后续会添加mybatis-plus提供数据库访问。

也可以使用https://start.spring.io/网站来生成子项目(最主要依赖是Spring Web):

生成后修改说明:

  1. 修改生成项目的父工程指向我们自定义的父工程。
  2. 如果再网站生成的工程,需要在父级工程的pom.xml中把子工程module配置进去:<module>simple-boot-demo</module>
  3. 一般情况下,我们都安装有自己maven,不需要嵌入的maven wrapper,可以删除mvnw相关文件。
  4. 如果有写死的依赖版本,建议移到父级工程统一管理。
  5. 建议修改application.properties为application.yml,yml格式是更好用的配置文件,尤其是对象、数组、键值对等支持比较好。

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.mengstudy</groupId>
        <artifactId>simple-boot-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.mengstudy</groupId>
    <artifactId>simple-boot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-boot-demo</name>
    <description>Demo project for simple Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--通常最基础可运行是选择spring-boot-starter-web,下面是可选配置-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--测试相关-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

简单测试子项目

修改启动文件SimpleBootDemoApplication,用向导生成项目的时候这个文件会自动生成。添加@RestController,然后添加注解方法。

启动项目:在idea中直接右键此文件,弹出菜单中选Debug或者Run即可,也可以用maven命令mvn spring-boot:run启动,此命令使用了maven插件spring-boot-maven-plugin,此插件在pom.xml中已经配置好:

@RestController
@SpringBootApplication
public class SimpleBootDemoApplication {

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

   @RequestMapping("/hello")
   public String hello(){
      return "Hello World!";
   }
}

访问http://localhost:8080/hello,可以看到有Hello World!输出,即表示成功了。

另外可以引入spring-boot-starter-actuator提供一些统计状态信息:

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

actuator信息输出,地址:http://localhost:8080/actuator,json返回里面会显示一些可以访问的地址

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/actuator",
      "templated": false
    },
    "health": {
      "href": "http://localhost:8080/actuator/health",
      "templated": false
    },
    "health-path": {
      "href": "http://localhost:8080/actuator/health/{*path}",
      "templated": true
    },
    "info": {
      "href": "http://localhost:8080/actuator/info",
      "templated": false
    }
  }
}

配置application.yml

Spring Boot项目使用此配置文件,可以配置SpringBoot项目信息,如名称、端口,日志等。

YAML格式中文参考:http://www.ruanyifeng.com/blog/2016/07/yaml.html

此文件默认为空文件,默认不配置端口的话是8080端口。

简单配置:

server:
  port: 8080
spring:
  application:
    name: simple-boot-demo

添加数据库访问

目前参考mybatis-plus提供基本数据库访问例子,稍作修改使用。

参考文档:https://mp.baomidou.com/guide/quick-start.html

基本数据定义

db/schema-h2.sql

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
   id BIGINT(20) NOT NULL COMMENT '主键ID',
   name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
   birth timestamp NULL DEFAULT NULL COMMENT '生日',
   email VARCHAR(200) NULL DEFAULT NULL COMMENT '邮箱',
   PRIMARY KEY (id)
);

db/data-h2.sql

DELETE FROM user;

INSERT INTO user (id, name, birth, email) VALUES
(1, 'Gary', '2000-01-01', 'gary@mengstudy.com'),
(2, 'Jerry', '2000-01-02', 'jerry@mengstudy.com'),
(3, 'Tom', '2000-01-03', 'tom@mengstudy.com')

添加Mybatis-Plus配置

父级配置上版本号和依赖管理

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <!--目前properties中配置mybatis-plus-boot-starter.version为3.3.1-->
    <version>${mybatis-plus-boot-starter.version}</version> 
</dependency>

子项目引入mybatis-plus,以及h2内嵌数据库:

<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>

添加数据库配置

在application.yml中添加数据库相关配置:

server:
  port: 8080
spring:
  application:
    name: simple-boot-demo
  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    data: classpath:db/data-h2.sql
    url: jdbc:h2:mem:simpledb
    username: root
    password: 123456
  h2:
    console:
      enabled: false

配置说明:

  1. 由于使用嵌入的内存H2数据库,用户、密码、数据库名称等都可以随便写,启动的时候生成。
  2. 启动时会根据schema和data配置的sql,建立表结构和插入数据。
  3. 默认情况下会有h2的控制台,启动项目后可以通过它管理数据库,地址如下:http://localhost:8080/h2-console
  4. 通过spring.h2.console.enabled=true控制是否开启控制台。
  5. 另外spring.h2.console.settings.web-allow-others=true,开启后控制台可以在远程访问。

实体和Mapper

目前使用Mybatis-Plus简化测试,没有特殊定制,可以不用xml文件。

User实体类:

@Data
public class User {
    private Long id;
    private String name;
    private Date birth;
    private String email;
}

UserMapper类:

public interface UserMapper extends BaseMapper<User> {
}

数据库访问测试

SimpleBootDemoApplication添加MapperScan扫描包@MapperScan("com.mengstudy.simple.boot.demo.mapper")

引入UserMapper,然后查询测试

@RestController
@MapperScan("com.mengstudy.simple.boot.demo.mapper")
@SpringBootApplication
public class SimpleBootDemoApplication {

   @Autowired
   private UserMapper userMapper;

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

   @RequestMapping("/hello")
   public String hello(){
      return "Hello World!";
   }

   @RequestMapping("/users")
   public List<User> users(){
      return userMapper.selectList(null);
   }

}

启动项目,测试访问:http://localhost:8080/users

输出:

[{
    "id": 1,
    "name": "Gary",
    "birth": "1999-12-31T16:00:00.000+0000",
    "email": "gary@mengstudy.com"
}, {
    "id": 2,
    "name": "Jerry",
    "birth": "2000-01-01T16:00:00.000+0000",
    "email": "jerry@mengstudy.com"
}, {
    "id": 3,
    "name": "Tom",
    "birth": "2000-01-02T16:00:00.000+0000",
    "email": "tom@mengstudy.com"
}]
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇