说明
- 项目基于idea+maven
- 代码github位置:https://github.com/ydfind/java-blog/tree/master/firstboot
- 最终项目目录:
程序
1 idea新建maven项目,项目名称“first-boot”
2 添加依赖,pom添加下面
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<!-- 继承spring boot的starter -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<!-- 添加web starter的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3 编写控制器
package com.ydfind.blog.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author ydfind
* @create 2019-04-05 15:10
*/
@Controller
public class FirstBootController {
@GetMapping("/hello")
@ResponseBody
public String hello(){
return "Hello World";
}
}
4 编写启动类
package com.ydfind.blog.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author ydfind
* @create 2019-04-05 15:07
*/
@SpringBootApplication
public class FirstBootMainApp {
public static void main(String[] args){
SpringApplication.run(FirstBootMainApp.class, args);
}
}
5 运行
启动FirstBootMainApp类的main函数:
服务器运行jar
若需要idea编译成jar,在centos运营,则pom.xml还需要
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
流程总结
- 建立maven项目
- pom添加parent的spring-boot-starter-parent(版本2.1.5.RELEASE),和spring-boot-starter-web;
- 写启动类。@SpringBootApplication、SpringApplication.run(main.class, args);
- 写controller类。@RestController,@GetMapping的hello函数
- 启动程序,访问hello接口验证