SpringBoot创建Web项目
本文适配的SpringBoot版本为2.6.3
最基础的web项目
使用IDEA2018创建第一个SpringBoot的Web项目。
(1)选择Spring Initializer
(2)注意Artifact不能出现大写英文字母,这里使用“-”作为多个单词的分隔。
(3)选择Web选项卡,勾选SpringWeb,这样pom.xml会引入依赖spring-boot-starter-web。
(4)项目工作空间
点击finish,项目创建完毕。
项目结构如下:
pom.xml文件依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
第一个依赖spring-boot-starter-web就是应用于web场景的,第二个依赖spring-boot-starter-test用于单元测试。
对于web应用来说,这是最基础的两个依赖。
此时,启动项目后,我们就可以通过localhost:8080访问应用了。
spring-boot-starter和spring-boot-starter-web
在上面的例子中,我在创建项目的时候勾选了SpringWeb,此时pom.xml文件会引入spring-boot-starter-web。
如果不勾选,直接点击“next”,此时pom文件只会引入spring-boot-starter。
spring-boot-starter-web包含了spring-boot-starter,所以使用spring-boot-starter-web就等于是有了spring-boot-starter的功能,除非只是要使用spring-boot-starter启动项目,而又不想引用过多的jar包时才用spring-boot-starter。
实际开发中不会只引入spring-boot-starter。
使用IDEA创建SpringBoot项目,如果不引入任何依赖,pom.xml依赖默认只有spring-boot-starter和单元测试的spring-boot-starter-test:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
对于项目集成各种依赖,我们可以在创建项目之初通过勾选各种Dependencies的方式进行,或者创建最基本的web项目后,直接修改pom.xml文件。
集成持久层框架
集成mybatis
项目启动时选择集成mybatis:
或者直接修改pom文件,加入mybatis的依赖、连接MySQL数据库的依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
集成mybatis-plus
开发工具
lombok
依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>