本轮笔记从0开始学习SpringBoot的工程搭建、开发、打包、部署等一系列知识,希望对您有用。
前提知识:安装好IDEA的电脑环境。可见IDEA安装教程。
搭建SpringBoot工程有两种,一种是新建Maven工程的方式;另外一种是利用SpringBoot Starter新建工程的方式。下面我给大家一一道来。
1,新建Maven工程的方式
打开IDEA,点击Create New Project

左边选择Maven,然后点击Next。

输入包名和工程名,点击Next。

输入Application 的名称,点击Finish。

工程会加载一堆东西,等加载完之后,我们可以看到左边的工程结构。src是代码,pom.xml为工程的配置文件。

我们打开工程的配置文件,加入一些springboot的配置信息(此时我们的左下角会让你选择是否自动加载的选项,点击Enable即可自动更新)。

<**parent**>
<**groupId**>org.springframework.boot</**groupId**>
<**artifactId**>spring-boot-starter-parent</**artifactId**>
<**version**>2.2.0.RELEASE</**version**>
<**relativePath**/>
*<!-- lookup parent from repository -->*
</**parent**>
<**dependencies**>
<**dependency**>
<**groupId**>org.springframework.boot</**groupId**>
<**artifactId**>spring-boot-starter-web</**artifactId**>
</**dependency**>
</**dependencies**>
加入上诉配置之后,工程就会自动加载新的配置包,直到他完成为止。

添加SpringBoot的包之后,我们可以在工程的相应位置添加Application类文件和Controller类文件。

@SpringBootApplication是标注这个类文件为启动文件。
package com.answer.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 标注是一个主程序
*/
@SpringBootApplication
public class HelloWorldMain {
public static void main(String[] args){
SpringApplication.run(HelloWorldMain.class,args);
}
}
@Controller标注这个类文件为一个控制器
@ResponseBody说明本方法返回Json数据
@RequestMapping("/hello")说明该方法的的请求地址
package com.answer.test.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "Hello world!";
}
}


完成这两个类的添加后,右击HelloWorldMain,Run'HelloWorldMain'。之后可以看到工程开启完毕。

可以在浏览器输入localhost:8080/hello

另外一种执行方式:打成jar包执行
在pom.xml上面添加Maven构建工具的依赖。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
等待依赖文件下载完毕之后,点击右边的Maven->Lifecycle,双击package进行打包操作。

一段时间后可以看到控制台显示Build success

我们可以在target文件上面看到打成的jar包。

进入jar包的目录文件,按住Shift键之后鼠标右击->在此处打开控制台,输入java -jar Helloworld-1.0-SNAPSHOT.jar后回车。

可以看到工程开启成功。

我们可以观看Helloworld-1.0-SNAPSHOT.jar这个jar包的工程结构,看到jar包自带tomcat的依赖文件,所以就算不用配置tomcat都可以执行工程。

利用Spring Initializr新建工程
新建工程,选择Spring Initializr。注意JDK的选择。

输入包名等信息。

选择各种依赖包,此处我们就只选择web的starter作为Demo。

下一步输入工程名。

点击完成后,其他事情跟前面的用maven新建工程的后续步骤一样,这种方法能够比较方便地加入依赖包。

新建的工程已经加入很多依赖的包。

如果加入的依赖没有自动加入,可以用下面的方法重新Reimport。

网友评论