前提
公司的基于Spring Boot的框架产品也用了一段时间了,但是也仅仅局限于基础应用,很多东西不知道是干啥的,很多很好的功能或特性没有充分利用,于是就打算系统完整地学习一下这个东西,从无到有,从写一个最简单的基于spring Boot的web服务端程序,到集成spring cloud 体系中大部分常用功能,有益于日后的工作。写一个系列博客,作为笔记。
目标
- 基于Myeclipse创建一个最低限度的spring boot工程;
- 创建一个可访问的接入服务;
工具
- JDK 1.8.0
- Myeclipse 2017 Stable 2.0
- Apache Maven 3.6.0
注 :myeclipse中有关maven的配置请自行百度
步骤
创建
- 在Myeclipse中新建maven project,如图:
注意勾选Create a simple project
-
填写坐标信息
父级工程的信息可以在此填写,也可暂时不填,创建成功以后写进pom.xml,具体信息如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
创建成功以后可以看到一个标准的maven工程的结构:
完善pom.xml文件内容如下:
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<groupId>com.terry</groupId>
<artifactId>spring-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springDemo</name>
<description>ReLearning Spring Boot form now on!</description>
<properties>
<java.version>1.8</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>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
其中spring-boot-starter-test可以先不要,开发测试的时候才会用到。
这时候就有一个问题,spring项目的配置文件有*.properties 和*.yml两种,按照我们平时开发的习惯应该采用application.yml格式的。那么采用哪种格式的配置文件是由什么决定的呢?答案是直接创建就行了,容器会自己判断的。
遂在src\main\resources\目录下创建配置文件application.yml,编辑内容如下:
server:
port: 9082 #服务端口号,默认8080
注:要注意yml的格式,次级节点要有四个空格的缩进,冒号后面要有一个空格。
创建启动类SpringBootDemoApplication.java,内容:
package com.terry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
一个工程只能有一个@SpringBootApplication注解,此时已经可以成功启动,并用配置的端口访问本工程了,但是没有任何对外接口:
建一个DemoRestController.java:
package com.terry.rest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class DemoRestController {
@RequestMapping("resource")
public String resurce(){
return "Hello Spring Boot!";
}
}
重启,用 http://localhost:9082/resource访问:
完事儿。