如何理解Spring Boot简介与配置

46次阅读
没有评论

共计 9181 个字符,预计需要花费 23 分钟才能阅读完成。

这篇文章给大家介绍如何理解 Spring Boot 简介与配置,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1 Spring Boot 简介与配置 1.1 Spring Boot

 Spring Cloud 基于 Spring Boot 搭建,本小节将对 Spring Boot 作一个大致的讲解,读者知道 Spring Boot 作用即可。

1.1.1 Spring Boot 简介

  开发一个全新的项目,需要先进行开发环境的搭建,例如要确定技术框架以及版本,还要考虑各个框架之间的版本兼容问题,完成这些繁琐的工作后,还要对新项目进行配置,测试能否正常运行,最后才将搭建好的环境提交给项目组的其他成员使用。经常出现的情形是,表面上已经成功运行,但部分项目组成员仍然无法运行,项目初期浪费大量的时间做这些工作,几乎每个项目都会投入部分工作量来做这些固定的事情。

  受 Ruby On Rails、Node.js 等技术的影响,JavaEE 领域需要一种更为简便的开发方式,来取代这些繁琐的项目搭建工作。在此背景下,Spring 推出了 Spring Boot 项目,该项目可以让使用者更快速的搭建项目,使用者可以更专注、快速的投入到业务系统开发中。系统配置、基础代码、项目依赖的 jar 包,甚至是开发时所用到的应用服务器等,Spring Boot 已经帮我们准备好,只要在建立项目时,使用构建工具加入相应的 Spring Boot 依赖包,项目即可运行,使用者无需关心版本兼容等问题。

 Spring Boot 支持 Maven 和 Gradle 这两款构建工具。Gradle 使用 Groovy 语言进行构建脚本的编写,与 Maven、Ant 等构建工具有良好的兼容性。鉴于笔者使用 Maven 较多,因此本书使用 Maven 作为项目构建工具。笔者成书时,Spring Boot 最新的正式版本为 1.5.4,要求 Maven 版本为 3.2 或以上。

1.1.2 新建 Maven 项目

  在新建菜单中选择新建“Maven Project”,填写的项目信息如图 2 - 5 所示。

图 2 -5 新建 Maven 项目

  为了测试项目的可用性,加入 Spring Boot 的 web 启动模块,让该项目具有 Web 容器的功能,pom.xml 文件内容如代码清单 2 - 1 所示。

  代码清单 2 -1:codes\02\env-test\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 
 groupId org.crazyit.cloud /groupId 
 artifactId env-test /artifactId 
 version 0.0.1-SNAPSHOT /version 
 dependencies 
dependency 
 groupId org.springframework.boot /groupId 
 artifactId spring-boot-starter-web /artifactId 
 version 1.5.4.RELEASE /version 
 /dependency
 /dependencies 
 /project

配置完依赖后,该依赖会自动帮我们的项目加上其他的 Spring 模块以及所依赖的第三方包,例如 spring-core、sprin-beans、spring-mvc 等,除了这些模块外,还加入了嵌入式的 Tomcat。

1.1.3 编写启动类

  加入了依赖后,只需要编写一个简单的启动类,即可启动 Web 服务,启动类如代码清单 2 - 2 所示。

  代码清单 2 -2:codes\02\env-test\src\main\java\org\crazyit\cloud\MyApplication.java

package org.crazyit.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);
}

 MyApplication 类使用了 @SpringBootApplication 注解,该注解声明了该类是一个 Spring Boot 应用,该注解具有“@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan”等注解的功能。直接运行 MyApplication 的 main 方法,看到以下输出信息后,证明成功启动:

2017-08-02 20:53:05.327 INFO 1976 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-02 20:53:05.530 INFO 1976 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-08-02 20:53:05.878 INFO 1976 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-02 20:53:05.885 INFO 1976 --- [ main] org.crazyit.cloud.MyApplication : Started MyApplication in 5.758 seconds (JVM running for 6.426)

  根据输出信息可知,启动的 Tomcat 端口为 8080,打开浏览器访问:http://localhost:8080,可以看到错误页面,表示应用已经成功启动。

1.1.4 编写控制器

  在前面小节加入的 spring-boot-starter-web 模块,默认集成了 SpringMVC,因此只需要编写一个 Controller,即可实现一个最简单的 HelloWord 程序,代码清单 2 - 3 为控制器。

  代码清单 2 -3:codes\02\env-test\src\main\java\org\crazyit\cloud\MyController.java

package org.crazyit.cloud;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class MyController {@GetMapping( /hello)
 @ResponseBody
 public String hello() {return  Hello World}

  代码清单 2 - 3 中使用了 @Controller 注解来修饰 MyController,由于启动类中使用了 @SpringBootApplication 注解,该注解含有 @ComponentScan 的功能,因此 @Controller 会被扫描并注册。在 hello 方法中使用了 @GetMapping 与 @ResponseBody 注解,声明 hello 方法的访问地址以及返回内容。重新运行启动类,打开浏览器并访问以下地址:http://localhost:8080/hello,可以看到控制器的返回。

1.1.5 发布 REST WebService

 Spring MVC 支持直接发布 REST 风格的 WebService,新建测试的对象 Person,如代码清单 2 - 4 所示。

  代码清单 2 -4:codes\02\env-test\src\main\java\org\crazyit\cloud\Person.java

package org.crazyit.cloud;
public class Person {
 private Integer id;
 private String name;
 private Integer age;
 public Integer getId() {
 return id;
 public void setId(Integer id) {
 this.id = id;
 public String getName() {
 return name;
 public void setName(String name) {
 this.name = name;
 public Integer getAge() {
 return age;
 public void setAge(Integer age) {
 this.age = age;

}

  修改控制器类,修改后如代码清单 2 -5。

  代码清单 2 -5:codes\02\env-test\src\main\java\org\crazyit\cloud\MyController.java

package org.crazyit.cloud;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {@GetMapping( /hello)
 public String hello() {
 return  Hello World 
 @RequestMapping(value =  /person/{personId} , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
 public Person findPerson(@PathVariable( personId) Integer personId) {Person p = new Person();
 p.setId(personId);
 p.setName( Crazyit 
 p.setAge(30);
 return p;
}

 MyController 类中,将原来的 @Controller 注解修改为 @RestController,原来的 hello 方法也不需要再使用 @ResponseBody 进行修饰,@RestController 已含有 @ResponseBody 注解。新建 findPerson 方法,该方法将会根据参数 id 来创建一个 Person 实例并返回,访问该方法将会得到 JSON 字符串。运行启动类,在浏览器中输入:http://localhost:8080/person/1,可看到接口返回以下 JSON 字符串:

{id :1, name : Crazyit , age :30}

  调用 REST 服务的方式有很多,此部分内容将在后面章节中讲述。

1.2 Spring Boot 配置文件

 Spring Cloud 基于 Spring Boot 构建,很多模块的配置均放在 Spring Boot 的配置文件中,因此有必要了解一下 Spring Boot 的配置文件规则,为学习后面的章节打下基础。

1.2.1 默认配置文件

 Spring Boot 会按顺序读取各种配置,例如命令行参数、系统参数等,本章只讲述配置文件的参数读取。默认情况下,Spring Boot 会按顺序到以下目录读取 application.properties 或者 application.yml 文件:

   项目根目录的 config 目录。

   项目根目录。

   项目 classpath 下的 config 目录。

   项目 classpath 根目录。

  如对以上描述有疑问,可参看图 2 -6。

图 2 -6 配置文件读取顺序

  图 2 - 6 中的数字为文件的读取顺序,本小节使用的 boot-config-file 项目依赖了 spring-boot-starter-web 项目,为 pom.xml 加入以下依赖:

dependency 
 groupId org.springframework.boot /groupId 
 artifactId spring-boot-starter-web /artifactId 
 version 1.5.4.RELEASE /version 
 /dependency

1.2.2 指定配置文件位置

  如果想自己指定配置文件,可以在 Spring 容器的启动命令中加入参数,例子如代码清单 2 - 6 所示。

  代码清单 2 -6:codes\02\boot-config-file\src\main\java\org\crazyit\boot\TestDefaultFile.java

package org.crazyit.boot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class TestDefaultFile {public static void main(String[] args) {
 ConfigurableApplicationContext context = new SpringApplicationBuilder(TestDefaultFile.class)
 .properties(spring.config.location=classpath:/test-folder/my-config.properties)
 .run(args);
 //  输出变量
 System.out.println(context.getEnvironment().getProperty(jdbc.user));
 }

 TestDefaultFile 类,在使用 SpringApplicationBuilder 时,配置了 spring.config.location 属性来设定需要读取的配置文件。

1.2.3 yml 文件

 YAML 语言使用一种方便的格式的来进行数据配置,通过配置分层、缩进,在很大程度上增强了配置文件的可读性,使用 YAML 语言的配置文件以“.yml”作为后缀。代码清单 2 - 7 为一份 yml 配置文件。

  代码清单 2 -7:codes\02\boot-config-file\src\main\resources\my-config.yml

jdbc:
 user:
 root
 passwd:
 123456
 driver:
 com.mysql.jdbc.Driver

  在此,需要注意的是,每一行配置的缩进要使用空格,不要使用 tab 键进行缩进。代码清单 2 - 7 对应的 properties 文件内容如下:

jdbc.user=root
jdbc.passwd=123456
jdbc.driver=com.mysql.jdbc.Driver

1.2.4 运行时指定 profiles 配置

  如果在不同的环境下激活不同的配置,可以使用 profiles,代码清单 2 - 8 中配置了两个 profiles。

  代码清单 2 -8:codes\02\boot-config-file\src\main\resources\test-profiles.yml

spring:
 profiles: mysql
jdbc:
 driver:
 com.mysql.jdbc.Driver
spring:
 profiles: oracle
jdbc:
 driver:
 oracle.jdbc.driver.OracleDriver

  定义了 mysql 与 oracle 两个 profiles,profiels 间使用“—”进行分隔,在 Spring 容器启动时,使用 spring.profiles.active 来指定激活哪个 profiles,如代码清单 2 - 9 所示。

  代码清单 2 -9:codes\02\boot-config-file\src\main\java\org\crazyit\boot\TestProfiles.java

package org.crazyit.boot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class TestProfiles {public static void main(String[] args) {
 ConfigurableApplicationContext context = new SpringApplicationBuilder(TestProfiles.class)
 .properties(spring.config.location=classpath:/test-profiles.yml)
 .properties(spring.profiles.active=oracle).run(args);
 //  输出变量
 System.out.println(context.getEnvironment().getProperty(jdbc.driver));
 //  启动第二个 Spring 容器,指定端口为 8081
 ConfigurableApplicationContext context2 = new SpringApplicationBuilder(TestProfiles.class)
 .properties(spring.config.location=classpath:/test-profiles.yml)
 .properties(spring.profiles.active=mysql).properties(server.port=8081).run(args);
 //  输出变量
 System.out.println(context2.getEnvironment().getProperty(jdbc.driver));
}

  对 Spring Boot 的配置文件有一定了解后,对后面章节 Spring Cloud 的配置内容就不会陌生。

1.2.5 热部署

  每次修改 Java 后,都需要重新运行 Main 方法才能生效,这样的会降低开发效果,我们可以使用 Spring Boot 提供的开发工具来实现热部署,为项目加上以下依赖:

dependency 
 groupId org.springframework.boot /groupId 
 artifactId spring-boot-devtools /artifactId 
 /dependency

  当 Java 文件修改后,容器会重新加载本项目的 Java 类。

丸趣 TV 小编主要讲述了本书基础环境的搭建,读者主要掌握 Maven 的使用,本书的案例几乎都是 Maven 项目。Spring Cloud 项目以 Spring Boot 作为基础进行构建,大部分案例也是基于 Spring Boot,本章对 Spring Boot 作了大致的讲解,并且配合一个 Hello World 例子来演示 Spring Boot 的便捷,学习完本章后,读者知道 Spring Boot 的大致功能,即可达到目标。

关于如何理解 Spring Boot 简介与配置就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-25发表,共计9181字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)