搭建第一个spring boot项目

时间:2023-03-08 22:37:59
搭建第一个spring boot项目

一、开发工具建议使用Spring Tool Suite

下载地址:http://spring.io/tools/sts/all/

点击versions选择相应的版本下载,解压后直接运行即可。

搭建第一个spring boot项目

二、创建项目

1、配置好Maven参数

2、创建一个spring starter project(设置相应参数),点击下一步

搭建第一个spring boot项目

3、选择spring boot 的版本,如果是web项目还有勾选web选项

搭建第一个spring boot项目

4、完成后如果pom.xml文件报错:failed to read artifact descriptor for org.springframework.boot:spring-boot-star

右键项目:maven/update project,勾选此选项

搭建第一个spring boot项目

5、项目创建成功后的目录结构

搭建第一个spring boot项目

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.xynet</groupId>
<artifactId>demo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo2</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties> <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> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

6、编写测试代码(新增controller)

搭建第一个spring boot项目

7、修改端口号为900,默认为:8080(在application.properties配置文件中修改)

搭建第一个spring boot项目

8、启动项目(运行下面的main方法即可)

搭建第一个spring boot项目

9、注意:如果想通过controller直接访问页面,可在pom.xml中添加引用

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

因为 spring-boot-starter-thymeleaf 包含了spring-boot-starter-web所以前面的spring-boot-starter-web引用可以去掉了

另外:增加的html页面要放在templates下面,并且在项目下面创建webapp文件夹并放入对应的html文件否则无法访问到页面(如我的放在:D:\Workspaces\STS\demo1\src\main\webapp\main.html)。

搭建第一个spring boot项目