通过以下步骤,我们可以手工搭建一个基础的基于Spring Boot的Web项目。
一、新建一个空的Maven项目
使用任意工具或手动构建一个Maven工程。
二、修改pom.xml
- 添加Spring Boot的父级依赖,以及基础的starter
添加父级依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
解析:声明parent,即意味着我们的工程是spring-boot-starter-parent的一个子工程,在父工程中,spring boot已经为我们做好了很多的配置
添加基础的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
解析:当我们只是需要使用最基础的spring boot时,可以引入spring-boot-starter,声明parent,引入基础starter,我们的工程就是一个spring boot工程了,可以使用自动配置的相关功能了。
- 添加对Web支持的starter pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 添加Spring Boot的编译插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
三、入口函数
package com.baymax.study.study_springaop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
-
@SpringBootApplication是Spring Boot的核心注解,作用是开启自动配置;
-
在main函数中通过
SpringApplication.run(App.class, args)
启动我们的Spring Boot程序。 -
在启动时可能会遇到下面的问题:
** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.
这是因为将App.class被编译到了src目录下的缘故,在src下创建package并移动App到package下即可。
四、配置文件
Spring Boot项目支持properties和yaml文件作为配置文件,默认的配置文件名称为application,即application.properties或application.yml,两者任选其一即可。
在不创建application配置文件的情况下,Spring Boot项目也可以正常启动,此时Web的端口默认为8080,访问路径默认为/。
Maven项目在resources中新建配置文件即可。
- application.properties
server.port=8081
server.context-path=/study
- application.yml
server:
port: 8081
contextPath: /study