Spring Boot学习分享-基础篇(Sample)

Owen Jia 2018年10月16日 1,101次浏览

分享目标

项目构建工具spring-boot的存在
帮助入门spring-boot,如何掌握使用它
spring-boot核心功能介绍

它是什么?

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

You can use Spring Boot to create Java applications that can be started by using java -jar or more traditional war deployments. We also provide a command line tool that runs “spring scripts”.

Spring boot是一个标准规范,一套完整的构建体系;2.0.*后版本的基本覆盖工程方法面面。

它能做什么用?

官方口号 | Our primary goals are:

Provide a radically faster and widely accessible getting-started experience for all Spring development.

Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.

Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).

Absolutely no code generation and no requirement for XML configuration.

官方的Feature介绍:

Create stand-alone Spring applications

构建独立标准的Spring服务

Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

内置应用服务器

Provide opinionated 'starter' dependencies to simplify your build configuration

'starter'类包简化你配置,spring-boot-starter

Automatically configure Spring and 3rd party libraries whenever possible

自动化配置Spring和第三方库

Provide production-ready features such as metrics, health checks and externalized configuration

标准化功能:监控、健康检测、抽象化配置等等

Absolutely no code generation and no requirement for XML configuration

无XML配置,无创建启动code

用了它有哪些好处呢?

邓老爷子说的好:不管它黑猫白猫,逮到老鼠就是好猫。

我们就是:不管这东西多么牛逼,对我有用有好处就是好东西;否则,对不起请.....

回顾传统项目构建

这里选Web型项目来聊,后面默认都是

传统项目目录结构

tomcat部署目录

传统项目构建发布包方式:

  • 构建War包由应用服务器解析生成目录
  • 构建zip包,集成assembly自己编写启动脚本集成服务器等等

spring-boot又是什么样的结构

spring-boot项目目录

可执行jar

只需要将这个jar复制到服务器上,运行
java -jar bi-web.jar --spring.profiles.active=prod
服务器就启动完成

比较来看优缺点

1、没有webapp目录也没有讨厌的web.xml文件配置;
2、所有文件封装在一个jar内部,启动部署超级简单;有个理念:jar in jar,springboot扩展了资源读取协议‘!/’可以多层出现在资源URL中。jar:file:/tmp/target/demo-0.0.1-SNAPSHOT.jar!/lib/spring-beans-4.2.3.RELEASE.jar
如何我们想自己去读jar-jar中文件呢?
3、提过spring-boot-starter-parent这样依赖管理库,直接引入spring-boot-starter-*组件,不需要关系包的依赖关系和版本;

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.6.RELEASE</version>
</parent>

4、starter机制产品化的封装了常见工具:redis、mq、jpa,metrics、health checks等等,和对于他们的自动化配置和依赖jar管理;
5、热加载机制spring-boot-devtool自动加载修改的代码,不用你每次都重启;

亮点总结:

原来我们是走路去上班的,现在我们是开着车去上班

  1. 统一的依赖包管理:版本依赖统一化封装,简化引入成本
  2. 自动化配置理念:配置抽象和统一化、配置文件继承&分环境启动、插件引入自配置启动理念
  3. 服务发布部署内置简单化:唯一的JAR文件、内置应用服务器
  4. 集成很多成熟产品化的解决方案:集成监控体现、集成统一日志体系等产品

缺点呢?

项目构建越来越简单傻瓜化,门槛不断降低,工程师价值不断被弱化。
久而久之,我们会忘记底层是如何构建的,再往后我们都可能不会想的起来去看看。
内部封装了很多底层服务,不知所以的就把内存给吃光;很多是默认启动(特别是早期版本)的需要你主动去关闭。

我们如何去用它?

1、通过IDE工具maven-archetype-quickstart创建maven项目
1、pom.xml的parent继承spring-boot-starter-parent包
2、dependencies中引入spring-boot-starter-web包
3、创建启动入口类main class

@SpringBootApplication
public class WebApp {
    public static void main(String[] args){
        SpringApplication.run(WebApp.class, args);
    }
}
@SpringBootApplication
public class Application extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(Application.class);
	}

	public static void main(String[] args) throws Exception {
		SpringApplication.run(Application.class, args);
	}

}

4、IDE工具中启动这个main class即可
5、构建打包jar | war两种方式发布包

<packaging>war</packaging>
<!--
<packaging>jar</packaging>
-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-tomcat</artifactId>
	<scope>provided</scope>
</dependency>
<plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
	<configuration>
	<mainClass>${start-class}</mainClass>
	<addResources>true</addResources>
	</configuration>
	<executions>
		<execution>
			<goals>
				<goal>repackage</goal>
			</goals>
		</execution>
	</executions>
</plugin>

6、jar内部展开

├── META-INF
│   ├── MANIFEST.MF
│   └── maven
├── BOOT-INF
│   ├── classes
│   │   ├──com
│   │   ├──config
│   │   ├──static
│   │   └── application.yml
│   ├── lib
│   │   ├── aopalliance-1.0.jar
│   │   ├── spring-beans-4.2.3.RELEASE.jar
│   │   ├── ...
└── org
    └── springframework
        └── boot
            └── loader
                ├── ExecutableArchiveLauncher.class
                ├── JarLauncher.class
                ├── JavaAgentDetector.class
                ├── LaunchedURLClassLoader.class
                ├── Launcher.class
                ├── MainMethodRunner.class
                ├── ...

推荐大家通过bi-parent项目来学习,作为spring-boot入门;

推荐使用官方推荐构建:Spring Initializr

亮点功能介绍

spring-boot-devtools

  • automatic restart: Applications automatically restart whenever files on the classpath change
  • livereload: It module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.
  • global setting: Any properties added to this file apply to all Spring Boot applications on your machine that use devtools.
  • remote application: You should never enable support on a production deployment.

nosql technologies

Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr Cassandra, Couchbase, and LDAP.

spring-boot-starter-test

  • JUnit: The de-facto standard for unit testing Java applications.
  • Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications.
  • AssertJ: A fluent assertion library.
  • Hamcrest: A library of matcher objects (also known as constraints or predicates).
  • Mockito: A Java mocking framework.
  • JSONassert: An assertion library for JSON.
  • JsonPath: XPath for JSON.

auto-configuration

针对服务的配置进行标准化,致力于最小化配置集成启动服务。

spring-boot-starter-actuator

Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application.

Endpoints: 提供一套服务监控接口,通过http请求获取服务运行状态,http://localhost:8080/test001/actuator/health 返回json格式数据。
Metrics: 监控组件,spring-boot将它完美融入的系统内,让你很方便的在restTemplate\cache\mvc\dataSource等模块去使用它。比如统计controller的api请求次数。

Spring Boot CLI

命令行工具:创建项目、启动服务、打包等等

freemarker|thymeleaf 服务器端java模版引擎

友情链接

多看看文档,多看博客

spring-boot

spring-framework

spring-boot-doc-2.0.6

bi-parent 专门构建的基础项目sample,减少大家重复造轮子

run-scripts 专门为可执行jar方式启动、关闭服务写的脚本


想要在技术的海洋里遨游,我们都需要有颗虔诚的心

From Owen Jia,推荐关注 Owen Jia Blog

欢迎收藏文章

手机端地址