一起来学SpringBoot | 第一篇:构建第一个SpringBoot工程
文章目录
- 引言
- 设计的目标
- 前提
- 创建项目
4.1. 目录结果
4.2. pom.xml 依赖
4.3. 主函数入口
4.4. 初窥配置文件
4.5. 测试 - 拓展知识
5.1. 自定义Banner - 总结
- 说点什么
1. 引言
SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我>们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB >工程
未接触 SpringBoot 之前,搭建一个普通的 WEB 工程往往需要花费30分钟左右,如果遇到点奇葩的问题耽搁的时间会更长一点,但自从用了SpringBoot 后,真正体会到什么叫分分钟搭建一个WEB,让我拥有更多的时间跟我的小伙伴们唠嗑了。使用 SpringBoot 后发现一切是如此的简单(还记得读书那会被JAR包,xml支配的恐惧吗,如今都可以说 good bye)
2. 设计的目标
- 为所有使用 Spring 的开发者提供一个更简单,快速的入门体验
- 提供一些常见的功能、如监控、WEB容器,健康,安全等功能
- 干掉XML,遵循规范,开箱即用
3. 前提
SpringBoot 为我们提供了一系列的依赖包,所以需要构建工具的支持:Maven 或 Gradle。由于本人更习惯使用Maven所以后续案例都是基于Maven 与 IntelliJ IDEA,同时这里是基于最新的SpringBoot2编写的哦…
4.创建项目
初次接触,我们先来看看如何创建一个Spring Boot项目,这里以IntelliJ IDEA为例,其他的IDE工具小伙伴们自行搜索创建方式。创建完项目后,各位小伙伴请认真、细心的对比下与传统的WEB工程有何区别(如:目录结构)。
点击File -> Project
如果用过 Eclipse/IDEA 等工具的,对创建项目肯定不会陌生,但为了照顾第一次使用的我贴上了图文
选择Spring Initializr
填写项目基本信息
- Group: 组织ID,一般分为多个段,这里我只说两段,第一段为域,第二段为公司名称。域又分为 org、
com、cn等等,其中 org为非营利组织,com为商业组织。如阿里、淘宝(com.alibaba/com.taobao) - Artifact: 唯一标识符,一般是项目名称
选择包
Spring Initializr 为我们提供了很多的选项,不同的选项有不同的作用,在初期我们只需要依赖Web -> Web 就可以了,选择好依赖包之后点击Next -> Finish
4.1. 目录结果
1 - src 2 -main 3 -java 4 -package 5 #主函数,启动类,运行它如果运行了 Tomcat、Jetty、Undertow 等容器 6 -SpringbootApplication 7 -resouces 8 #存放静态资源 js/css/images 等 9 - statics 10 #存放 html 模板文件 11 - templates 12 #主要的配置文件,SpringBoot启动时候会自动加载application.yml/application.properties 13 - application.yml 14 #测试文件存放目录 15 -test 16 # pom.xml 文件是Maven构建的基础,里面包含了我们所依赖JAR和Plugin的信息 17 - pom
4.2. pom.xml 依赖
因为使用了 Spring Initializr 插件,所以如下的配置都不需要我们自己去写啦,需要注意的是版本要选择 RELEASE ,稳定版本BUG少
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 6 <groupId>com.battcn</groupId> 7 <artifactId>chapter1</artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 <packaging>jar</packaging> 10 11 <name>chapter1</name> 12 <description>我的用第一个SpringBoot工程</description> 13 14 <!--版本采用的是最新的 2.0.1.RELEASE TODO 开发中请记得版本一定要选择 RELEASE 哦 --> 15 <parent> 16 <groupId>org.springframework.boot</groupId> 17 <artifactId>spring-boot-starter-parent</artifactId> 18 <version>2.0.1.RELEASE</version> 19 <relativePath/> <!-- lookup parent from repository --> 20 </parent> 21 22 <properties> 23 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 24 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 25 <java.version>1.8</java.version> 26 </properties> 27 28 <dependencies> 29 <!-- 默认就内嵌了Tomcat 容器,如需要更换容器也极其简单--> 30 <dependency> 31 <groupId>org.springframework.boot</groupId> 32 <artifactId>spring-boot-starter-web</artifactId> 33 </dependency> 34 <!-- 测试包,当我们使用 mvn package 的时候该包并不会被打入,因为它的生命周期只在 test 之内--> 35 <dependency> 36 <groupId>org.springframework.boot</groupId> 37 <artifactId>spring-boot-starter-test</artifactId> 38 <scope>test</scope> 39 </dependency> 40 </dependencies> 41 42 <build> 43 <plugins> 44 <!-- 编译插件 --> 45 <plugin> 46 <groupId>org.springframework.boot</groupId> 47 <artifactId>spring-boot-maven-plugin</artifactId> 48 </plugin> 49 </plugins> 50 </build> 51 52 53 </project>
其它的依赖可以参考:官方文档
4.3. 主函数入口
注意事项: 一个项目中切记不要出现多个 main 函数,否在在打包的时候 spring-boot-maven-plugin 将找不到主函数(主动指定打包主函数入口除外…)
1 /** 2 * 我的第一个SpringBoot程序 3 * 其中 @RestController 等同于 (@Controller 与 @ResponseBody) 4 * 5 * @author Levin 6 */ 7 @RestController 8 @SpringBootApplication 9 public class Chapter1Application { 10 11 public static void main(String[] args) { 12 SpringApplication.run(Chapter1Application.class, args); 13 } 14 15 @GetMapping("/demo1") 16 public String demo1() { 17 return "Hello battcn"; 18 } 19 20 @Bean 21 public CommandLineRunner commandLineRunner(ApplicationContext ctx) { 22 // 目的是 23 return args -> { 24 System.out.println("来看看 SpringBoot 默认为我们提供的 Bean:"); 25 String[] beanNames = ctx.getBeanDefinitionNames(); 26 Arrays.sort(beanNames); 27 Arrays.stream(beanNames).forEach(System.out::println); 28 }; 29 } 30 }
4.4. 初窥配置文件
从启动日志中可以发现,SpringBoot 默认的端口是 8080 ,那么如果端口被占用了怎么办呢?不要慌,问题不大,配置文件分分钟解决你的困扰…
2018-04-20 16:14:46.725 INFO 11184 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
修改默认配置
1 # 默认的 8080 我们将它改成 9090 2 server.port=9090 3 # 未定义上下文路径之前 地址是 http://localhost:8080 定义了后 http://localhost:9090 你能在tomcat做的事情,配置文件都可以 4 server.servlet.context-path=/chapter1
在启动一次看看日志
2018-04-20 16:47:05.716 INFO 12108 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path '/chapter1'
4.5. 测试
本次测试采用 junit 进行,当然也可以启动项目后直接访问 http://localhost:9090/chapter/demo1 进行测试
1 import org.junit.Before; 2 import org.junit.Test; 3 import org.junit.runner.RunWith; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.boot.test.context.SpringBootTest; 6 import org.springframework.boot.test.web.client.TestRestTemplate; 7 import org.springframework.boot.web.server.LocalServerPort; 8 import org.springframework.http.ResponseEntity; 9 import org.springframework.test.context.junit4.SpringRunner; 10 11 import java.net.URL; 12 13 import static org.junit.Assert.assertEquals; 14 15 @RunWith(SpringRunner.class) 16 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 17 public class Chapter1ApplicationTests { 18 19 20 @LocalServerPort 21 private int port; 22 23 private URL base; 24 25 @Autowired 26 private TestRestTemplate template; 27 28 @Before 29 public void setUp() throws Exception { 30 // TODO 因为我们修改了 content-path 所以请求后面要带上 31 this.base = new URL("http://localhost:" + port + "/chapter1/demo1"); 32 } 33 34 @Test 35 public void demo1() throws Exception { 36 ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); 37 assertEquals(response.getBody(), "Hello battcn"); 38 } 39 }
5. 拓展知识
5.1. 自定义Banne
SpringBoot 启动的时候我们可以看到如下内容,这一块其实是可以自定义的哦,而且在 2.X 版本中,它支持的格式从文本扩展到banner.txt、banner.jpg、banner.gif、banner.jpeg 等等,只需要在 resouces 目录下添加指定命名的文件即可
1 . ____ _ __ _ _ 2 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ 3 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ 4 \\/ ___)| |_)| | | | | || (_| | ) ) ) ) 5 ' |____| .__|_| |_|_| |_\__, | / / / / 6 =========|_|==============|___/=/_/_/_/ 7 :: Spring Boot :: (v2.0.1.RELEASE)
6. 总结
目前很多大佬都写过关于 SpringBoot 的教程了,如有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE编写,包括新版本的特性都会一起介绍…