SpringBoot官方文档翻译(七):增加类路径依赖

11.2 Adding Classpath Dependencies(增加类路径依赖)

1
2
3
4
5
6
Spring Boot provides a number of “Starters” that let you add     
jars to your classpath. Our sample application has already
used spring-boot-starter-parent in the parent section of the POM.
The spring-boot-starter-parent is a special starter that provides
useful Maven defaults. It also provides a dependency-management 
section so that you can omit version tags for “blessed” dependencies.

Spring Boot 提供了一些“Starters”用于您增加一些jars包到您的类路径下。我们的示例应用已经使用了spring-boot-starter-parent在上一节的POM文件中。spring-boot-starter-parent是一个提供了非常有用的Maven默认的特殊的starter。它同样提供了一个dependency-management部分,以便于您可以为一些“幸福”依赖忽略版本标签。

1
2
3
4
5
Other “Starters” provide dependencies that you are likely to need     
when developing a specific type of application. Since we are
developing a web application, we add a spring-boot-starter-web 
dependency. Before that, we can look at what we currently have
by running the following command:

其他“Starters”提供了一些依赖,以便于您可以在开发一些特殊模式的应用,如果我们需要部署一个web应用,我们需要增加 spring-boot-starter-web的依赖。在此之前,我们可以使用以下命令寻找我们目前已有的依赖:

1
2
3
$ mvn dependency:tree

[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT

1
2
3
4
5
The mvn dependency:tree command prints a tree representation of     
your project dependencies. You can see that spring-boot-starter-parent 
provides no dependencies by itself. To add the necessary dependencies,
edit your pom.xml and add the spring-boot-starter-web dependency
immediately below the parent section:

mvn dependency:tree命令会将您的应用依赖以树形展示。您可以发现spring-boot-starter-parent本身并不提供任何依赖。如果需要增加必要的依赖,更改您的pom.xml,增加spring-boot-starter-web依赖紧接在父节点下面:

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

1
2
3
If you run mvn dependency:tree again, you see that there are now a     
number of additional dependencies, including the Tomcat web server
and Spring Boot itself.

如果您再次运行mvn dependency:tree,您将会看到一系列的新增的依赖,包括tomcat服务器和Spring Boot本身

分享到

SpringBoot官方文档翻译(六):创建POM文件

11.1 Creating the POM(创建POM文件)

1
2
3
We need to start by creating a Maven pom.xml file. The pom.xml is     
the recipe that is used to build your project. Open your favorite
text editor and add the following:

我们需要以创建一个pom.xml文件开始。pom.xml是用于构建项目的配方。 打开您最喜欢的文本编辑器并添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<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>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</version>
</parent>

<!-- Additional lines to be added here... -->

<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
1
2
3
The preceding listing should give you a working build. You can     
test it by running mvn package (for now, you can ignore the “jar
will be empty - no content was marked for inclusion!” warning).

上面的列表应该已经给了您一个可工作的构建。您可以使用mvn package来运行测试它(现在,你可以忽略“jar will be empty - no content was marked for inclusion!“的警告)

1
2
3
At this point, you could import the project into an IDE (most     
modern Java IDEs include built-in support for Maven). For simplicity,
we continue to use a plain text editor for this example.

在此刻,您可以导入该工程到IDE(所有的流行的javaIDE都支持导入Maven项目)。为了简化,我们继续使用纯文本编辑器编辑示例。

分享到

SpringBoot官方文档翻译(四):安装Spring Boot命令行界面

10.2 Installing the Spring Boot CLI(安装Spring Boot命令行界面)

1
2
3
4
5
6
7
The Spring Boot CLI (Command Line Interface) is a command line tool    
that you can use to quickly prototype with Spring. It lets you
run Groovy scripts, which means that you have a familiar Java-like
syntax without so much boilerplate code.
You do not need to use the CLI to work with Spring Boot, but
it is definitely the quickest way to get a Spring application
off the ground.

Spring Boot CLI(命令行界面)是一个命令行工具,您可以使用它来快速使用Spring进行原型开发
它允许您运行Groovy脚本,这意味着您不需要太多样板代码就能以类似于java的语法进行开发。
尽管您不需要使用CLI去运行Spring Boot ,但这绝对是获得Spring应用程序的最快捷方式

10.2.1 Manual Installation(手动安装)

1
2
3
4
5
6
7
8
9
10
You can download the Spring CLI distribution from the Spring     
software repository:
• spring-boot-cli-2.1.0.BUILD-SNAPSHOT-bin.zip
• spring-boot-cli-2.1.0.BUILD-SNAPSHOT-bin.tar.gz
Cutting edge snapshot distributions are also available.
Once downloaded, follow the INSTALL.txt instructions from the
unpacked archive. In summary, there is a spring script (spring.bat 
for Windows) in a bin/directory in the .zip file. Alternatively,
you can use java -jar with the .jar file (the script helps you to
be sure that the classpath is set correctly).

您可以从Spring 软件远程库下载Spring CLI的分发版本
• spring-boot-cli-2.1.0.BUILD-SNAPSHOT-bin.zip
• spring-boot-cli-2.1.0.BUILD-SNAPSHOT-bin.tar.gz
最新的快照版本同样可用。下载以后,请参照解压出来的文档INSTALL.txt的介绍进行操作。综上所述,有一个spring脚本(windows 下用spring.bat)在bin目录下的.zip文件中。另外,你可以使用java -jar 启动.jar包(这个脚本帮助您确认类路径是否被正确设置)

10.2.2 Installation with SDKMAN!(通过SDKMAN安装)

1
2
3
4
SDKMAN! (The Software Development Kit Manager) can be used for     
managing multiple versions of various binary SDKs, including Groovy
and the Spring Boot CLI. Get SDKMAN! from sdkman.io and install
Spring Boot by using the following commands:

SDKMAN!(软件开发工具包管理器)可用于管理各种二进制SDK的多个版本,包括Groovy脚本和Spring Boot CLI.从sdkman.io中获取SDKMAN!并用以下命令进行Spring Boot 安装。

1
2
3
$ sdk install springboot
$ spring --version
Spring Boot v2.1.0.BUILD-SNAPSHOT

1
2
If you develop features for the CLI and want easy access     
to the version you built, use the following commands:

如果您为CLI开发功能并希望轻松访问您创建的版本,请使用以下命令:

1
2
3
4
5
$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/    
target/spring-boot-cli-2.1.0.BUILD-SNAPSHOT-bin/spring-2.1.0.BUILD-SNAPSHOT/
$ sdk default springboot dev
$ spring --version
Spring CLI v2.1.0.BUILD-SNAPSHOT
1
2
The preceding instructions install a local instance of spring called the dev instance. It points at your target build location, so every time you rebuild Spring Boot,spring is up-to-date.
You can see it by running the following command:

之前介绍了如何安装一个被称之为dev实例的本地spring实例。它指向了您的目标构建地址,因此每次当您重新构建Spring Boot的时候spring也同步更新。您可以通过运行下列命令行查看它:

1
2
3
4
5
6
7
8
9
10
11
12
13
$ sdk ls springboot

================================================================================
Available Springboot Versions
================================================================================
> + dev
* 2.1.0.BUILD-SNAPSHOT

================================================================================
+ - local version
* - installed
> - currently in use
================================================================================

10.2.3 OSX Homebrew Installation(苹果系统下使用Homebrew安装)

1
2
If you are on a Mac and use Homebrew, you can install the     
Spring Boot CLI by using the following commands:

如果您使用的是Mac并且使用Homebrew命令,你可以安装Spring Boot CLI 通过以下命令:

1
2
$ brew tap pivotal/tap
$ brew install springboot
1
Homebrew installs spring to /usr/local/bin.

Homebrew将spring安装在/usr/local/bin路径下

1
2
If you do not see the formula, your installation of brew     
might be out-of-date. In that case, run brew update and try again.

如果您没有看到该公式,那么您的brew的安装可能会过时。 在这种情况下,运行brew update并重试。

10.2.4 MacPorts Installation(以MacPorts安装方式)

1
2
If you are on a Mac and use MacPorts, you can install the     
Spring Boot CLI by using the following command:

如果您使用Mac,并且使用MacPorts,您可以通过以下命令安装Spring Boot CLI

1
$ sudo port install spring-boot-cli

10.2.5 Command-line Completion(命令行完成)

1
2
3
4
5
6
7
8
9
The Spring Boot CLI includes scripts that provide command     
completion for the BASH and zsh shells. You can source 
the script (also named spring) in any shell or put it in
your personal or system-wide bash completion initialization.
On a Debian system, the system-wide scripts are in 
/shell-completion/bash and all scripts in that directory
are executed when a new shell starts. For example, to run
the script manually if you have installed by using SDKMAN!,
use the following commands:

Spring Boot CLI为BASH和zsh shells提供了命令行完成脚本。您可以在任何shell或者您个人的或者系统范围内的bash中初始化source该脚本。在Debian系统,全系统脚本在/shell-completion/bash,并且所有新建的可执行脚本都在该路径下。比如说,在您已经安装使用SDKMAN的情况下,去手动运行该脚本,使用如下命令:

1
2
3
$ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring
$ spring <HIT TAB HERE>
grab help jar run test version

1
2
3
If you install the Spring Boot CLI by using Homebrew or MacPorts,     
the command-line completion scripts are automatically registered
with your shell.

如果您使用Homebrew或者MacPorts安装Spring Boot CLI命令行初始化完成,那么它会自动注册到您的shell当中。

10.2.6 Quick-start Spring CLI Example(快速开始Spring CLI 示例)

1
2
You can use the following web application to test your installation.     
To start, create a file called app.groovy, as follows:

您可以使用如下的web应用去测试您的安装情况。首先,创建一个如下的app.groovy:

1
2
3
4
5
6
7
8
9
@RestController
class ThisWillActuallyRun {

@RequestMapping("/")
String home() {
"Hello World!"
}

}
1
Then run it from a shell, as follows:

然后在shell中运行它,如下:

1
$ spring run app.groovy

1
2
The first run of your application is slow, as dependencies     
are downloaded. Subsequent runs are much quicker.

首次运行您的应用会比较慢,因为依赖库需要被下载,以后每次运行会比较快

1
2
Open localhost:8080 in your favorite web browser.     
You should see the following output:

在您喜爱的浏览器中打开 localhost:8080 ,您将会看到如下的输出:

1
Hello World!

10.3 Upgrading from an Earlier Version of Spring Boot(从一个旧版本升级Spring Boot)

1
2
3
4
If you are upgrading from an earlier release of Spring Boot, check     
the “migration guide” on the project wiki that provides detailed
upgrade instructions. Check also the“release notes” for a list of
“new and noteworthy” features for each release.

如果您想从以前的版本中升级Spring Boot 请核对该项目在wiki上的“migration guide”,它提供了详细的升级说明。并且从列表中核对“relese notes”,每个relese版本都有新的值得注意的功能。

1
2
3
4
5
To upgrade an existing CLI installation, use the appropriate     
package manager command (for example, brew upgrade) or, if
you manually installed the CLI, follow thestandard instructions,
remembering to update your PATH environment variable to
remove any older references.

去升级一个已有的CLI安装程序,推荐使用打包工具命令(比如 brew upgrage),如果您手动安装了CLI,根据标准的说明,记得更新您的环境变量去移除任何旧的关联

分享到

SpringBoot官方文档翻译(五):部署你的第一个Spring Boot应用

11. Developing Your First Spring Boot Application(部署你的第一个Spring Boot应用)

1
2
3
This section describes how to develop a simple “Hello World!” web     
application that highlights some of Spring Boot’s key features. We
use Maven to build this project, since most IDEs support it.

本节讲述了如何部署一个简单的”Hello World”的Web应用,突出讲述了一些Spring Boot的关键功能。我们使用Maven去构建这个工程,因为大多数IDE支持它。

1
2
3
4
5
6
7
The spring.io web site contains many “Getting Started” guides that     
use Spring Boot. If you need to solve a specific problem, check
there first.You can shortcut the steps below by going to 
start.spring.io and choosing the "Web" starter from the
dependencies searcher. Doing so generates a new project structure
so that you can start coding right away. Check the Spring Initializr
documentation for more details.

spring.io网站包含了很多使用Spring Boot的“入门”向导。如果你需要解决一个特殊的问题,可以首先从那里寻找答案。您可以通过start.spring.io从依赖中找到“Web starter”来简化以下步骤。这样做会产生一个新的项目结构,以便您可以立即开始编码。查看Spring Initializr文档以获取更多详细信息。

1
2
Before we begin, open a terminal and run the following commands    
to ensure that you have valid versions of Java and Maven installed:

在我们开始之前,打开terminal窗口,运行以下指令去确认您是否安装有符合版本的java和maven

1
2
3
4
$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

1
2
3
4
$ mvn -v
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
This sample needs to be created in its own folder. Subsequent     
instructions assume that you have created a suitable folder and     
that it is your current directory.

此示例需要在其自己的文件夹中创建。随后说明假定您已经创建了合适的文件夹和
它是你当前的目录。

分享到

SpringBoot官方文档翻译(三):安装部署Spring Boot

10. Installing Spring Boot(安装部署Spring Boot)

1
2
3
4
5
6
7
8
9
Spring Boot can be used with “classic” Java development tools     
or installed as a command line tool. Either way, you need 
Java SDK v1.8 or higher. Before you begin, you should check
your current Java installation by using the following command:
$ java -version
If you are new to Java development or if you want to experiment
with Spring Boot, you might want to try the Spring Boot CLI 
(Command Line Interface) first. Otherwise, read on for “classic”
installation instructions.

Spring Boot 可以被传统的java部署工具部署,也可以被安装为命令行工具。同样的,您需要java1.8或更高的版本支持。在您开始之前,您可以使用如下命令检查一下您的JDK版本

1
$ java -version

如果您是新部署一个应用或者您想尝试下Spring Boot ,您可以首先尝试使用Spring Boot CLI(命令行接口)。否则,请阅读“传统”安装介绍。

10.1 Installation Instructions for the Java Developer(针对java开发者的安装介绍)

1
2
3
4
5
6
7
8
9
10
You can use Spring Boot in the same way as any standard Java library.    
To do so, include the appropriate spring-boot-*.jar files on your
classpath. Spring Boot does not require any special tools integration,
so you can use any IDE or text editor. Also, there is nothing special
about a Spring Boot application, so you can run and debug a
Spring Boot application as you would any other Java program.

Although you could copy Spring Boot jars, we generally recommend
that you use a build tool that supports dependency management (such
as Maven or Gradle).

您可以同样的使用Spring Boot作为一个标准的Java库。因此,您可以讲spring-boot-*.jar适当的引入到您的类路径下。Spring Boot不需要任何特殊的工具集成,因此您可以使用任何IDE或文本编辑器。并且,Spring Boot应用没有任何特殊之处,因此您可以像运行其他任何Java程序一样运行和调试Spring Boot应用程序。尽管您可以拷贝Spring Boot jar包,但我们通常建议您使用支持依赖管理的构建工具(如Maven或Gradle)。

10.1.1 Maven Installation(Maven下的安装)

1
2
Spring Boot is compatible with Apache Maven 3.2 or above. If you do    
not already have Maven installed, you can follow the instructions at maven.apache.org.

Spring Boot与Apache Maven 3.2或更高版本兼容。 如果你
尚未安装Maven,您可以按照maven.apache.org上的说明进行操作。

1
2
3
4
5
On many operating systems, Maven can be installed with a package     
manager. If you use OSX Homebrew, try brew install maven.
Ubuntu users can run sudo apt-get install maven. Windows users
with Chocolatey can run choco install maven from an elevated
(administrator) prompt.

在很多系统中,Maven可以使用包管理器进行安装。如果您使用OSX系统的Homebrew,尝试
brew install maven。Ubuntu用户可以运行 sudo apt-get 安装maven。 具有Chocolatey命令行管理包的Window用户可以以管理员的身份在示框中运行choco install maven

1
2
3
4
5
6
Spring Boot dependencies use the org.springframework.boot groupId.    
Typically, your Maven POM file inherits from the spring-boot-starter-
parentproject and declares dependencies to one or more “Starters”.
Spring Boot also provides an optional Maven plugin to create
executable jars.
The following listing shows a typical pom.xml file:

Spring Boot 依赖使用 org.springframework.boot 作为groupId。通常,您的Maven POM文件继承于spring-boot-starter-parentproject 并且声明依赖于一个或者多个“Straters”。Sring Boot同样提供了可选的Maven插件去创建可运行jars包。以下列表展示了一个通常使用的pom.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<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>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>

<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</version>
</parent>

<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<!-- Add Spring repositories -->
<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>

10.1.2 Gradle Installation(Gradle下的安装)

1
2
3
4
5
6
7
Spring Boot is compatible with Gradle 4. If you do not already    
have Gradle installed, you can follow the instructions at gradle.org.
Spring Boot dependencies can be declared by using the org.springframework.boot group.
Typically, your project declares dependencies to one or
more“Starters”. Spring Boot provides a useful Gradle plugin 
that can be used to simplify dependency declarations and to
create executable jars.

Spring Boot 兼容Gradle 4. 如果您还没有安装Gradle,您可以从 gradle.org中获取介绍文档。
Spring Boot依赖可以被声明为org.springframework.boot group。通常,您的项目被声明依赖于一个或者多个“Strarters”。Spring Boot 提供可用的Gradle 插件用于简化依赖声明和创建可执行jars包。

1
2
3
4
5
Gradle Wrapper
The Gradle Wrapper provides a nice way of “obtaining” Gradle when
you need to build a project. It is a small script and library that
you commit alongside your code to bootstrap the build process.
See docs.gradle.org/4.2.1/userguide/gradle_wrapper.html for details.

Gradle 包装
当您去构建您的应用时,Gradle 包装提供了一个优雅的路径去“获得”Gradle。他提供了一个小脚本和库似的您的提交和构建同步进行。具体参见:docs.gradle.org/4.2.1/userguide/gradle_wrapper.html

1
The following example shows a typical build.gradle file:

以下为一个通常的build.gradle文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
buildscript {
repositories {
jcenter()
maven { url 'https://repo.spring.io/snapshot' }
maven { url 'https://repo.spring.io/milestone' }
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.1.0.BUILD-SNAPSHOT'
}
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

jar {
baseName = 'myproject'
version = '0.0.1-SNAPSHOT'
}

repositories {
jcenter()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}

dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
分享到

SpringBoot官方文档翻译(二):系统依赖

9 . System Requirements(系统依赖)

1
2
3
Spring Boot 2.1.0.BUILD-SNAPSHOT requires Java 8 or 9 and     
Spring Framework 5.0.5.RELEASE or above. Explicit build
support is provided for Maven 3.2+ and Gradle 4.

Spring Boot 2.1。0.BUILD-SNAPSHOT 需要java8或者java9版本,以及Spring Framework 5.0.5.RELEASE 或更高版本。为Maven 3.2+和Gradle 4提供了明确的支持。

9.1 Servlet Containers(Servlet 容器)

1
Spring Boot supports the following embedded servlet containers:

Spring Boot支持如下内置容器

Name Servlet Version
Tomcat 8.5 3.1
Jetty 9.4 3.1
Undertow 1.4 3.1
1
You can also deploy Spring Boot applications to any Servlet 3.1+ compatible container.

您也可以部署Spring Boot应用在任何的基于Servlet 3.1+版本的容器中

分享到

SpringBoot官方文档翻译(一):介绍 Spring Boot

Part II. Getting Started

篇章二. 开始

1
2
3
4
5
6
If you are getting started with Spring Boot,or “Spring” in general, 
start by reading this section. It answers the basic “what?”, “how?”
and “why?” questions.It includes an introduction to Spring Boot,
along with installation instructions.We then walk you through
building your first Spring Boot application, discussing some core
principles as we go.

一般来说,您可以从阅读本章节开始学习Spring Boot 或者Spring。本节回答了最基础的“什么?”,“如何?”,“为何?”等问题。它包括了介绍Spring Boot如何独立部署的说明。我们将带领您建设您得第一个SpringBoot应用,跟随我们一起去探讨一些Spring Boot的核心价值。

8 . Introducing Spring Boot(介绍 Spring Boot)

1
2
3
4
5
Spring Boot makes it easy to create stand-alone, production-grade     
Spring-based Applications that you can run. We take an opinionated
view of the Spring platform and third-party libraries, so that you
can get started with minimum fuss. Most Spring Boot applications
need very little Spring configuration.

Spring Boot使您能够非常简单的创建一个可运行的基于Spring的,产品级别的,独立部署应用。我们用我们自己认为的观点来处理Spring平台和第三方库,以便于您能够以最小的代价开始您的应用。所有的Spring Boot应用都只需要很少的Spring配置

1
2
3
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 中使用java -jar 或者更为传统的 war包去创建java应用。我们同样提供了命令行工具去运行“Spring脚本”。

1
2
3
4
5
6
7
8
9
10
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.

我们的主要目标
• 为所有的基于Spring的开发提供一个更快的,更广泛的入门级体验。
• 以自我认为的方式通过一些默认的最快速基本的配置实现开箱即用的体验。
• 提供大型项目(如内置服务器,安全性,埋点,运行状况检查和外部配置)通用的一系列非产品功能性的功能。
• 绝对不需要生成代码或者xml的配置。

分享到

消除过期的对象引用(六)

消除过期的对象引用

书中的例子如下:问题出在pop方法上,pop出去以后,stack的size本身减少1,size–,外部会持有该对象的引用,但是即便外部释放掉该element的引用,stack本身还有一个“保护机制”,栈内部会维护着这个对象的过期引用。
为什么呢?
这个是数组的特性,好比创建了一个16大小的数组,调用pop方法相当于这时候对第16个数组对象创建一个外部引用,这个对象本身还是在内存中有空间的。换而言之,这个第16个对象此时此刻即被外部调用的一个引用持有,也同时被stack本身的数组持有,也许有人认为–size了,现在应该变为15大小的数组了,为什么还持有第16个呢?
这里首先要理解数组对象创建的时候内存的变化。声明数组过程中,变量保存在栈中,创建并进行初始化时,数组元素是保存在堆中,数组通过引用指针指向数组元素。
对于基本类型数组的初始化,程序直接先为数组分配内存空间,再将数组元素的值存入对应的内存里。
对于引用类型数组的数组元素依然是引用类型,因此数组元素里存储的还是引用,它指向另一块内存,该内在里存储了该引用变量所引用的对象。
这里的size其实只是栈中一个域变量的变化,而非真正数组的变化,原来作为基本类型的引用依然存在于第16个数组的位置上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Stack {
pprivate Object[] elements;
private int size = 0;
private static final int DEFAULT_INITAL_CAPACITY = 16;

public Stack() {
elements = new Object[DEFAULT_INITAL_CAPACITY];
}

public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}

public Object pop() {
if(size == 0) {
throw new EmptyStackException();
}
return elements[--size];
}

private void ensureCapacity() {
if(elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}

术语:过期引用(obsolete reference) ,指永远不会被解除的引用。

书中也给了修改得方式如下:

1
2
3
4
5
6
7
8
public Object pop(){
    if(size == 0){
        throw new EmptyStackException();
    }
    Object result = elements[--size];
    elements[size] = null;
    return result;
}

分享到

私有化构造函数强化不可实例化的类,避免创建不必要的对象(四,五)

通过私有化构造函数强化不可实例化的类

这个个人理解就是因为有默认构造函数的原因,如果是显示声明私有化的话则不可实例化,或者只能通过本身来提供实例。但是对于某些工具类,如Collections,更希望即便在内部也不要私有化,书中给出一种方案,我们一Collections类为例

1
2
3
4
// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
throw new AssertionError();//可有可以无,但是有的情况下,可以有效防止内部不小心实例化
}

避免创建不必要的对象

其实鼓励能够使用单例的或者静态工厂的尽量使用,这样可以少创建无用对象,这样能减轻垃圾回收的压力,可以很好的提升性能。

1
2
3
4
String s = new String("stringette");
//这种写法会制造不必要的String实例,"stringette"本身就是一个实例,再使用new会再创建一个实例
String ss = "stringette";
//这种写法会复用一个实例,即便在多次调用的情况下,该实例被保存在字符串常量池中

可以参考下这篇文章:https://www.cnblogs.com/ydpvictor/archive/2012/09/09/2677260.html

优先使用基本类型,而非装箱类型,这里装箱的时候回产生新的对象。
下面这个例子测试时间分别为8483ms和775ms相差有10倍之多

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.stardust.effective.role4And5;

/**
* Created by mike on 2017/12/4.
*/
public class LongTest {

public static void main(String[] args) {
long start = System.currentTimeMillis(); //获取开始时间
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
long middle = System.currentTimeMillis(); //获取中间时间
System.out.println(middle-start);



long sum2 = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum2 += i;
}
long end = System.currentTimeMillis(); //获取结束时间
System.out.println(end-middle);
}

}

分享到

用私有构造器或者枚举强化单例(三)

用私有构造器或者枚举强化单例

首先对单单例,构造函数需要私有化,这样能够极大的保障外部无法直接实例化该对象
单例在面试中经常会有面试官要求写,下面列出几种常用的写法:

懒汉式(线程不安全写法,与之相对的还有线程安全的写法不赘述)

1
2
3
4
5
6
7
8
9
10
 public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}   
    public static Singleton getInstance() {  
     if (instance == null) {  
          instance = new Singleton();  
      }  
      return instance;  
      }  
   }

饿汉式(线程不安全写法,与之相对的还有线程安全的写法不赘述)

1
2
3
4
5
6
7
 public class Singleton {  
     private static Singleton instance = new Singleton();  
     private Singleton (){}
     public static Singleton getInstance() {  
     return instance;  
     }  
 }

对于上面这种写法,在书中有提到如果首行代码是public的话可以通过反射机制多实例化对象。如下举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.stardust.effective.role3;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
* Created by mike on 2017/12/3.
*/
public class Singleton {

public static Singleton instance = new Singleton();

private Singleton() { }

public static Singleton getInstance() {
return instance;
}

public static void main(String[] args) {
Singleton s1 = null;
Singleton s2 = null;
Singleton s3 = Singleton.getInstance();
Singleton s4 = Singleton.getInstance();

if (s3==s4){
System.out.println("通过静态工厂获取到的单例是唯一的");
}else {
System.out.println("静态工厂获取的单例不唯一");
}

Constructor<?> constructor = Singleton.class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
try {
s1 = (Singleton) constructor.newInstance();
s2 = (Singleton) constructor.newInstance();
if(s1!=s2){
System.out.println("构造出两个不同的实例");
}else {
System.out.println("始终为单例");
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}

}

枚举实现单例,这个是effective java书中推荐的实现方式,枚举天然私有构造,final,static等特性,可以生产一个懒加载的单例

1
2
3
4
5
6
public enum Singletons {
    INSTANCE;
    public void say() {
        System.out.println("animal say");
    }
}

从网上找的一个具体的例子,SomeThing.INSTANCE.getInstance() 即可获得所要实例

1
2
3
4
5
6
7
8
9
10
11
12
13
class Resource{
}

public enum SomeThing {
INSTANCE;
private Resource instance;
SomeThing() {
instance = new Resource();
}
public Resource getInstance() {
return instance;
}
}

分享到