SpringBoot官方文档翻译(十七):Spring Beans和依赖注入

17. Spring Beans and Dependency Injection(Spring Beans和依赖注入)

1
2
3
4
5
You are free to use any of the standard Spring Framework     
techniques to define your beans and their injected dependencies.
For simplicity, we often find that using @ComponentScan 
(to find your beans) and using @Autowired (to do constructor
injection) works well.

您可以自由的使用Spring框架标注的一些技术和注解来定义您的注入依赖关系。打个比方,我们经常使用
@ComponentScan(去查找您的beans),用@Autowired(去做构造注入)。

1
2
3
4
5
If you structure your code as suggested above (locating your     
application class in a root package), you can add @ComponentScan 
without any arguments. All of your application components
(@Component, @Service, @Repository, @Controller etc.) are
automatically registered as Spring Beans.

如果您按照以上的建议构造您的代码结构(将您的主应用类放在根包下面),您可以增加@ComponentScan注解而不需要任何参数。您所有的应用组件(@Component, @Service, @Repository, @Controller 等等)都将被自动注册为Spring Beans。

1
2
The following example shows a @Service Bean that uses     
constructor injection to obtain a required RiskAssessor bean:

接下去的例子展示了@Service使用构造注入去获得必要的RiskAssessor bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}

// ...

}

1
2
If a bean has one constructor, you can omit the @Autowired,     
as shown in the following example:

如果一个bean有一个构造函数,您可以省略@Autowired注解,如下例子:

1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}

// ...

}

1
2
3
Notice how using constructor injection lets the riskAssessor     
field be marked as final, indicating that it cannot be
subsequently changed.

注意介绍如何使用构造注入使riskAssessor字段被标记为final,表明它不可以随后改变。

分享到

SpringBoot官方文档翻译(十六):自动配置

16. Auto-configuration(自动配置)

1
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.

Spring Boot 自动配置将根据您增加的jar包依赖关系尝试全自动的配置您的Spring应用。举个例子,如果HSQLDB在您的类路径下,而您未配置任何数据库连接beans,Spring将会自动配置一个基于内存的数据库。

1
2
3
You need to opt-in to auto-configuration by adding     
the @EnableAutoConfiguration or @SpringBootApplication 
annotations to one of your @Configuration classes.

您需要通过增加@EnableAutoConfiguration或者@SpringBootApplication注解到您的@Configuration配置类,以此来加入自动配置的功能。

1
2
3
4
You should only ever add one @SpringBootApplication or     
@EnableAutoConfiguration annotation. We generally
recommend that you add one or the other to your primary 
@Configuration class only.

您应该只添加@SpringBootApplication或者@EnableAutoConfiguration中的一个注解。我们一般建议您将一个或另一个添加到您的主@Configuration类。

16.1 Gradually Replacing Auto-configuration(逐渐替换自动配置)

1
2
3
4
Auto-configuration is non-invasive. At any point, you can start     
to define your own configuration to replace specific parts of the
auto-configuration. For example, if you add your own DataSource bean,
the default embedded database support backs away.

自动配置是非侵入式的。 在任何时候,您都可以开始定义自己的配置以替换自动配置的特定部分。
例如,如果您添加自己的DataSource bean,则默认的嵌入式数据库支持会被取消。

1
2
3
4
If you need to find out what auto-configuration is currently      
being applied, and why, start your application with the --debug switch.
Doing so enables debug logs for a selection of core loggers and logs
a conditions report to the console.

如果您需要了解当前正在应用的自动配置以及为什么被使用,采用–debug开关启动您的应用程序。
这样做可以启用debug断点日志作为主日志输出,记录各种条件分支报告到控制台。

16.2 Disabling Specific Auto-configuration Classes(禁用特定的自动配置类)

1
2
3
4
If you find that specific auto-configuration classes that you     
do not want are being applied, you can use the exclude attribute
of @EnableAutoConfiguration to disable them, as shown in the
following example:

如果您发现一些特殊的自动配置类,您并不想他们生效。您可以在@EnableAutoConfiguration注解中使用排除标签去禁用他们,如下例子:

1
2
3
4
5
6
7
8
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

1
2
3
4
If the class is not on the classpath, you can use the excludeName     
attribute of the annotation and specify the fully qualified name
instead. Finally, you can also control the list of auto-configuration
classes to exclude by using the spring.autoconfigure.exclude property.

如果该类不在类路径下,您可以使用该注解的excludeName属性去定义全路径名称来替代。最后,您可以通过使用spring.autoconfigure.exclude控制自动配置的类的列表。

1
2
You can define exclusions both at the annotation level and by     
using the property.

你既可以在注解中定义exclusions,也可以在property属性中定义。

分享到

SpringBoot官方文档翻译(十五):配置类

15. Configuration Classes(配置类)

1
2
3
4
5
Spring Boot favors Java-based configuration. Although it is     
possible to use SpringApplication with XML sources, we generally
recommend that your primary source be a single @Configuration class.
Usually the class that defines the main method is a good candidate
as the primary @Configuration.

Spring Boot偏向于使用Java-base的配置方式。尽管他也能够支持使用SpringApplication配合XML,我们通常还是强烈建议您使用单个的@Configuration注解类做配置类。通常定义main方法的类用来作为一个主配置类是一个很好的选择。

15.1 Importing Additional Configuration Classes(导入其他配置类)

1
2
3
4
5
You need not put all your @Configuration into     
a single class. The @Import annotation can be
used to import additional configuration classes.
Alternatively, you can use @ComponentScan to automatically
pick up all Spring components, including @Configuration classes.

您并不需要将您所有的配置放在一个@Configuration注解的类中。@Import注解可以用来导入额外的注解类。另外,您可以使用@ComponentScan注解去制动选择所有的Spring组件。包括@Configuration注解的配置类。

1
2
3
We recommend that you follow Java’s recommended package naming     
conventions and use a reversed domain name (for example, 
com.example.project).

我们建议您遵循Java推荐的软件包命名约定并使用反向域名(例如,com.example.project)。

15.2 Importing XML Configuration(导入XML配置)

1
2
3
If you absolutely must use XML based configuration, we recommend     
that you still start with a @Configuration class. You can then
use an @ImportResourceannotation to load XML configuration files.

如果您是在要使用基于XML的配置,我们建议您还是从一个@Configuration注解的类开始。您可以在其中使用@ImportResourceannotation注解去加载XML配置文件。

分享到

SpringBoot官方文档翻译(十四):组织你的代码

14. Structuring Your Code(组织您的代码)

1
2
Spring Boot does not require any specific code layout to work.     
However, there are some best practices that help.

Spring Boot不需要任何特殊的代码框架就能运行。然而,有一些最佳实践可以给予您更多的帮助。

14.1 Using the “default” Package(使用默认包)

1
2
3
4
5
6
When a class does not include a package declaration, it is     
considered to be in the “default package”. The use of the
“default package” is generally discouraged and should be
avoided. It can cause particular problems for Spring Boot
applications that use the @ComponentScan, @EntityScan, or @SpringBootApplicationannotations, since every class
from every jar is read.

当一个类不包含包声明时,它是被认为是在“默认包”中。 使用“默认包”通常是不鼓励的,应该是
避免。 它可能会导致Spring Boot的特殊问题,诸如在使用@ComponentScan,@EntityScan或@SpringBootApplicationannotations的应用程序,因为每个包里的每个类都会被读取。

1
2
3
We recommend that you follow Java’s recommended package naming     
conventions and use a reversed domain name (for example, 
com.example.project).

我们建议您遵循Java推荐的软件包命名约定并使用反向域名(例如,com.example.project)。

14.2 Locating the Main Application Class(定位主应用类)

1
2
3
4
5
6
7
We generally recommend that you locate your main application     
class in a root package above other classes .The @SpringBootApplication annotation is often placed
on your main class, and it implicitly defines a base “search
package” for certain items. For example, if you are writing a
JPA application, the package of the @SpringBootApplication annotated
class is used to search for @Entity items. Using a root package also
allows component scan to apply only on your project.

我们通常推荐您将主应用类放到高于其他的类的根目录。@SpringBootApplication注解一般用于您的主应用类上,它隐含地为某些项目定义了一个基础“搜索包”。举个例子,如果你正在写一个JPA应用程序,@SpringBootApplication注释类所在的包将会用于搜索@Entity注解。 使用根包也允许组件扫描仅适用于您的项目。

1
2
3
4
If you don’t want to use @SpringBootApplication,     
the @EnableAutoConfiguration and @ComponentScan 
annotations that it imports defines that behaviour
so you can also use that instead.

如果您不想使用注解@SpringBootApplication,注解@EnableAutoConfiguration@ComponentScan组合使用可以起到替代它的作用。

1
The following listing shows a typical layout:

以下的列表显示了一个典型的类和包结构布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java

1
2
The Application.java file would declare the main method,     
along with the basic @SpringBootApplication, as follows:

Application.java文件将定义main方法,已经基本的@SpringBootApplication如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
public class Application {

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

}

分享到

SpringBoot官方文档翻译(十三):Starters

13.5 Starters

1
2
3
4
5
6
7
Starters are a set of convenient dependency descriptors that     
you can include in your application. You get a one-stop shop
for all the Spring and related technologies that you need
without having to hunt through sample code and copy-paste
loads of dependency descriptors. For example, if you want
to get started using Spring and JPA for database access,
include the spring-boot-starter-data-jpa dependency in your project.

“Starters”是一组可以导入到您的应用中的方便可用的依赖描述符。您将可以在不需要通过示例代码搜索拷贝-粘贴的情况下一站式获得所有关于Spring相关联的技术依赖。举个例子,如果您选择使用Spring和JPA作为数据库接入组件,导入spring-boot-starter-data-jpa依赖进您的工程即可。

1
2
3
The starters contain a lot of the dependencies that you need     
to get a project up and running quickly and with a consistent,
supported set of managed transitive dependencies.

这些“Starters”包含很多您需要的让项目快速启动的依赖,并保持一致,支持一组受管控的传递依赖。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
What’s in a name
All official starters follow a similar naming pattern; 
spring-boot-starter-*, where * is a particular type of
application. This naming structure is intended to help
when you need to find a starter. The Maven integration
in many IDEs lets you search dependencies by name. For
example, with the appropriate Eclipse or STS plugin installed,
you can press ctrl-space in the POM editor and type
“spring-boot-starter” for a complete list.
As explained in the “Creating Your Own Starter” section,
third party starters should not start with spring-boot,
as it is reserved for official Spring Boot artifacts. Rather,
a third-party starter typically starts with the name of the project.
For example, a third-party starter project called thirdpartyproject 
would typically be named thirdpartyproject-spring-boot-starter.

名字中包含了什么?
所有的官方“starters”遵循一个相同的命名规范;spring-boot-starter-,
“是代表特定类型的应用。这种命名结构能够在您需要寻找一个“starter”的时候提供有利的帮助。
在许多集成了Maven的IDE中,您都可以按名称搜索依赖项。比如,通过安装适当的Eclipse或STS插件,
你可以在POM编辑器中按ctrl-space并键入“spring-boot-starter”获取完整列表。
如上所述,“创建您自己的Starter”,第三方“starters”不应该使用spring-boot作为开头,因为他是为官方Spring Boot保留的。然而,一个第三方的starter一般以工程名开始。举个例子,一个第三方的starter工程名为“thirdpartyproject”,可以以“thirdpartyproject-spring-boot-starter”来命名。

1
2
The following application starters are provided by Spring Boot    
under the org.springframework.boot group:

如下应用的starters被Spring Boot提供,在 org.springframework.boot group下

名字 描述
spring-boot-starter 核心starter, 包括自动配置支持, 日志和YMAL支持。
spring-boot-starter-activemq Starter用于JMS消息,使用Apache的ActiveMQ
spring-boot-starter-amqp Starter用于使用Spring AMQP 和Rabbit MQ
spring-boot-starter-aop Starter用于在Spring AOP 和 AspectJ下的面相切面编程
spring-boot-starter-artemis Starter用于JMS消息 ,应用于 Apache Artemis
spring-boot-starter-batch Starter 用于使用Spring Batch
spring-boot-starter-cache Starter用于使用Spring Framework下的缓存支持
spring-boot-starter-cloud-connectors Starter用于Spring Cloud连接,它简化了连接到Cloud Foundry和Heroku等云平台的服务
spring-boot-starter-data-cassandra Starter用于使用Cassandra分布式数据库和Spring Data Cassandra
spring-boot-starter-data-cassandra-reactive Starter用于使用Cassandra分布式数据库和Spring Data Cassandra Reactive
spring-boot-starter-data-couchbase Starter用于Couchbase面向文档的数据库和Spring Data Couchbase
spring-boot-starter-data-couchbase-reactive Starter用于使用Couchbase面向文档的数据库和Spring Data Couchbase Reactive
spring-boot-starter-data-elasticsearch Starter用于使用Elasticsearch 查找分析引擎 和 Spring Data Elasticsearch
spring-boot-starter-data-jpa Starter用于Spring Data JPA和Hibernate
spring-boot-starter-data-ldap Starter用于Spring Data LDAP
spring-boot-starter-data-mongodb Starter用于MongoDB 基于文档的数据库和Spring Data MongoDB
spring-boot-starter-data-mongodb-reactive Starter用于使用MongoDB面向文档的数据库和Spring Data MongoDB Reactive
spring-boot-starter-data-neo4j Starter用于使用Neo4j图形数据库和Spring Data Neo4jPom
spring-boot-starter-data-redis Starter用于在Spring Data Redis和Lettuce客户端中使用Redis键值数据存储
spring-boot-starter-data-redis-reactive Starter用于使用Redis键值数据存储以及Spring Data Redis反应器和Lettuce客户端
spring-boot-starter-data-rest Starter用于使用Spring Data REST将Spring Data存储库暴露于REST
spring-boot-starter-data-solr Starter用于在Spring Data Solr中使用Apache Solr搜索平台
spring-boot-starter-freemarker Starter用于基于FreeMarker View的MVC web应用
spring-boot-starter-groovy-templates Starter用于建设基于Groovy模板的MVC web应用
spring-boot-starter-hateoas Starter用于使用Spring MVC和Spring HATEOAS构建基于超媒体的RESTful Web应用程序
spring-boot-starter-integration Starter用于使用Spring Integration
spring-boot-starter-jdbc Starter用于使用JDBC和HikariCP连接池的入门者
spring-boot-starter-jersey Starter用于建设基于JAX-RS and Jersey的RESTful web应用Spring-Boot-Starter-Web的另一种选择
spring-boot-starter-jooq Starter用于JPPQ数据连接框架.spring-boot-starter-data-jpa 和 spring-boot-starter-jdbc的替代者
spring-boot-starter-json Starter用于读写json
spring-boot-starter-jta-atomikos Starter用于使用Atomikos的JTA事务
spring-boot-starter-jta-bitronix Starter用于使用Bitronix的JTA事务
spring-boot-starter-jta-narayana Starter用于使用Narayana的JTA事务
spring-boot-starter-mail Starter用于使用Java Mail 和 Spring Framework的email发送支持
spring-boot-starter-mustache Starter用于建设基于Mustache views的web应用
spring-boot-starter-quartz Starter用于Quartz scheduler定时器任务
spring-boot-starter-security Starter用于使用Spring Security
spring-boot-starter-test Starter用于测试Spring Boot应用包含JUnit, Hamcrest 和 Mockito
spring-boot-starter-thymeleaf Starter用于基于thymeleaf视图的的MVC应用建设
spring-boot-starter-validation Starter用于使用Java Bean的检验框架,基于hibernate的校验器
spring-boot-starter-web Starter用于构建web应用, 包含RESTful, 应用基于使用 Spring MVC. 使用Tomcat作为默认的容器
spring-boot-starter-web-services Starter用于使用Spring Web Services
spring-boot-starter-webflux Starter用于使用WebFlux Spring Framework’s Reactive Web 支持
spring-boot-starter-websocket Starter用于构建基于Spring Framwork的websocket支持
1
2
In addition to the application starters, the following     
starters can be used to add production ready features:

除了应用级别的starters以外,下面的这个starter具备产品级功能应用。

1
Table 13.2. Spring Boot production starters

Spring Boot的产品级starters
名字 | 描述
——— | ————-
spring-boot-starter-actuator|Starter用于Spring Boot 的 Actuator,它是用于提供产品级别的应用管理和监控功能

1
Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets:

最后,Spring Boot还提供了如下的starters用于帮助您排除或者替代的starters

1
Table 13.3. Spring Boot technical starters

Spring Boot技术starters
名字 | 描述
——— | ————-
spring-boot-starter-jetty|Starter用于使用基于servlet技术的内置jetty容器。 可以用于替代spring-boot-starter-tomcat
spring-boot-starter-log4j2|Starter用于基于log4j2的日志处理。可以替代现有的spring-boot-starter-logging
spring-boot-starter-logging|Starter用于基于Logback的日志处理. 也是默认的日志处理器。
spring-boot-starter-reactor-netty|Starter用于Reactor Netty作为内置容器的响应式HTTP 服务器.
spring-boot-starter-tomcat|Starter用于内置的Tomcat容器,如果使用spring-boot-starter-web依赖的话,会将此作为默认以来
spring-boot-starter-undertow|Starter用于基于undertow的内置容器,spring-boot-starter-tomcat的替代者。

1
2
For a list of additional community contributed starters, see the     
README file in the spring-boot-starters module on GitHub.

如果想要获得社区贡献的更多的starters,请阅读GitHub上spring-boot-starters模块的README文件。

分享到

SpringBoot官方文档翻译(十二):Gradle&Ant

13.3 Gradle

1
2
To learn about using Spring Boot with Gradle, please refer     
to the documentation for Spring Boot’s Gradle plugin:

学习在Spring Boot中使用Gradle请转到如下Spring Boot的Gradle插件关联文档中:
https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/gradle-plugin/reference/html/)

13.4 Ant

1
2
3
4
5
It is possible to build a Spring Boot project using Apache Ant+Ivy.     
The spring-boot-antlib “AntLib” module is also available to help
Ant create executable jars.
To declare dependencies, a typical ivy.xml file looks something
like the following example:

您同样可以使用Apache的Ant配合Ivy去构建Spring Boot工程。spring-boot-antlib 的“AntLib”模块同样可以帮助Ant创建可执行的jars包。
声明依赖,一个典型的ivy.xml文件如下:

1
2
3
4
5
6
7
8
9
10
11
<ivy-module version="2.0">
<info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
<configurations>
<conf name="compile" description="everything needed to compile this module" />
<conf name="runtime" extends="compile" description="everything needed to run this module" />
</configurations>
<dependencies>
<dependency org="org.springframework.boot" name="spring-boot-starter"
rev="${spring-boot.version}" conf="compile" />
</dependencies>
</ivy-module>

1
A typical build.xml looks like the following example:

一个典型的build.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
<project
xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:spring-boot="antlib:org.springframework.boot.ant"
name="myapp" default="build">

<property name="spring-boot.version" value="2.1.0.BUILD-SNAPSHOT" />

<target name="resolve" description="--> retrieve dependencies with ivy">
<ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
</target>

<target name="classpaths" depends="resolve">
<path id="compile.classpath">
<fileset dir="lib/compile" includes="*.jar" />
</path>
</target>

<target name="init" depends="classpaths">
<mkdir dir="build/classes" />
</target>

<target name="compile" depends="init" description="compile">
<javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
</target>

<target name="build" depends="compile">
<spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
<spring-boot:lib>
<fileset dir="lib/runtime" />
</spring-boot:lib>
</spring-boot:exejar>
</target>
</project>
1
2
3
If you do not want to use the spring-boot-antlib module,     
see the Section 86.9, “Build an Executable Archive from
Ant without Using spring-boot-antlib” “How-to” .

如果您不想使用spring-boot-antlib模块,请直接看章节86.9“Build an Executable Archive from Ant without Using spring-boot-antlib”

分享到

SpringBoot官方文档翻译(十一):使用Spring Boot&Maven

Part III. Using Spring Boot(使用Spring Boot)

1
2
3
4
5
6
7
This section goes into more detail about how you should use     
Spring Boot. It covers topics such as build systems, auto-configuration,
and how to run your applications. We also cover some Spring Boot
best practices. Although there is nothing particularly special about
Spring Boot (it is just another library that you can consume),
there are a few recommendations that, when followed, make your
development process a little easier.

本部分介绍了更多的关于您如何使用Spring Boot的细节。它涵盖了构建系统,自动配置,如何运行您的应用等主题。我们同样涉及了Spring Boot的最佳实践。尽管Spring Boot并没有什么非常特别的东西(它仅仅是您可消费的另一个库而已),接下去,有一些建议,可以使您的部署进程变得更加简单。

13. Build Systems(构建系统)

1
2
3
4
5
6
It is strongly recommended that you choose a build system that     
supports dependency management and that can consume artifacts
published to the “Maven Central” repository. We would recommend
that you choose Maven or Gradle. It is possible to get Spring Boot
to work with other build systems (Ant, for example), but they are
not particularly well supported.

我们强烈推荐您选择一款构建系统支持依赖管理的,并且能够发布到“Maven Central”库。我们推荐您选择Maven或者Gradle。当然,Spring Boot也同样能够作用于诸如Ant等构建工具,但是对于他们的支持并不是全面的。

13.1 Dependency Management(依赖管理)

1
2
3
4
5
6
Each release of Spring Boot provides a curated list of     
dependencies that it supports. In practice, you do not
need to provide a version for any of these dependencies
in your build configuration, as Spring Boot manages that
for you. When you upgrade Spring Boot itself, these
dependencies are upgraded as well in a consistent way.

Spring Boot的每个发行版都提供了一个它支持的依赖关系的策划列表。基于实践,在您的构建配置中您不需要为任何依赖提供一个版本。因为Spring Boot为您管理这些版本。当您升级Spring Boot本身的时候,这些依赖版本会以一致的方式很好的自动升级。

1
2
You can still specify a version and override Spring Boot’s     
recommendations if you need to do so.

如果您愿意的话,您依然可以指定一个版本覆盖Spring Boot建议的版本。

1
2
3
4
The curated list contains all the spring modules that you can use     
with Spring Boot as well as a refined list of third party libraries.
The list is available as a standard Bills of Materials (spring-boot-
dependencies) that can be used with both Maven and Gradle.

这个策划列表包含了所有的您可以配合Spring Boot 使用的spring模块和一个精简的第三方库。
这个列表可以作为一个标准的材料清单(spring-boot-dependencies)用于Maven或者Gradle。

1
2
Each release of Spring Boot is associated with a base version of the     
Spring Framework. We highly recommend that you not specify its version

每一个发布的Spring Boot版本会关联Spring的一个基础版本。我们高度推荐您不要自定义它的版本。

13.2 Maven

1
2
3
Maven users can inherit from the spring-boot-starter-parent     
project to obtain sensible defaults. The parent project
provides the following features:

Maven用户可以继承spring-boot-starter-parent 工程去获得合理的默认值。该父工程提供了如下的功能:

1
2
3
4
5
6
7
8
9
•	Java 1.8 as the default compiler level.
• UTF-8 source encoding.
• A Dependency Management section, inherited from the spring-boot-dependencies
pom, that manages the versions of common dependencies. This dependency management
lets you omit <version> tags for those dependencies when used in your own pom.
• Sensible resource filtering.
• Sensible plugin configuration (exec plugin, Git commit ID, and shade).
• Sensible resource filtering for application.properties and application.yml including profile-specific files
(for example, application-dev.properties and application-dev.yml)
  • java 1.8作为默认的编译等级
  • UTF-8作为源编码字符集
  • 依赖管理部分,继承于spring-boot-dependencies pom管理基础依赖版本。这种依赖管理能够让您在您的pom中忽略标签。
  • 恰到好处的资源过滤
  • 恰如其分的插件配置(exec plugin, Git commit ID, and shade)
  • 通过profile—specific为application.propertiesapplication.yml做恰当的资源文件过滤(例如application-dev.properties 和 application-dev.yml)
1
2
3
4
Note that, since the application.properties and application.yml     
files accept Spring style placeholders (${… }), the Maven filtering
is changed to use @..@placeholders. (You can override that by setting
a Maven property called resource.delimiter.)

注意,因为application.propertiesapplication.yml文件接收Spring风格的占位符(${… }),Maven过滤器变成使用@..@占位符。(您可以通过resource.delimiter文件设置Maven的属性覆盖maven的占位符。

13.2.1 Inheriting the Starter Parent(继承父Starter)

1
2
To configure your project to inherit from the     
spring-boot-starter-parent, set the parent as follows:

配置您的工程去继承spring-boot-starter-parent,设置父pom如下:

1
2
3
4
5
6
<!-- 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>
1
2
3
You should need to specify only the Spring Boot version number     
on this dependency. If you import additional starters, you can
safely omit the version number.

你仅仅只需要再依赖中定义Spring Boot的版本号。如果您想导入额外的starters,您可以安全的忽略版本号。

1
2
3
4
With that setup, you can also override individual dependencies     
by overriding a property in your own project. For instance, to
upgrade to another Spring Data release train, you would add the
following to your pom.xml:

用那个设置,您依然可以通过复写属性覆盖个人的依赖,例如,升级到另一个Spring Data的升级版,您可以增加以下配置到您的pom.xml中:

1
2
3
<properties>
<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>

1
Check the spring-boot-dependencies pom for a list of supported properties.

检查spring-boot-dependencies pom(https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-dependencies/pom.xml)以获取支持的属性列表

13.2.2 Using Spring Boot without the Parent POM(不使用父POM)

1
2
3
Not everyone likes inheriting from the spring-boot-starter-parent     
POM. You may have your own corporate standard parent that you need
to use or you may prefer to explicitly declare all your Maven configuration.

并不是每个人都喜欢用继承于spring-boot-starter-parent POM的方式。您可能需要使用您自己的团队标准的父POM,又或者您更愿意明确声明您所有的Maven配置

1
2
3
If you do not want to use the spring-boot-starter-parent, you can     
still keep the benefit of the dependency management (but not the
plugin management) by using a scope=import dependency, as follows:

如果您不愿使用spring-boot-starter-parent,您仍然可以通过使用scope=import依赖来保留依赖管理的价值,如下:

1
2
3
4
5
6
7
8
9
10
11
12
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
1
2
3
4
5
6
The preceding sample setup does not let you override individual     
dependencies by using a property, as explained above. To achieve
the same result, you need to add an entry in the dependencyManagement 
of your project before the spring-boot-dependencies entry.
For instance, to upgrade to another Spring Data release train,
you could add the following element to your pom.xml:

如上所述,上述示例设置不会让您通过使用属性覆盖个人依赖关系。为了达到同样目标,您需要在dependencyManagement中的spring-boot-dependencies前使用一个节点。举个例子,升级另一个Spring Data 发行版本,您可以增加如下的元素到您的pom.xml中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<dependencyManagement>
<dependencies>
<!-- Override Spring Data release train provided by Spring Boot -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Fowler-SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

1
2
In the preceding example, we specify a BOM, but any     
dependency type can be overridden in the same way.

在之前的例子中,我们定义了一个清单,但是任何的依赖类型都能够以这种方式进行覆盖。

13.2.3 Using the Spring Boot Maven Plugin

1
2
3
Spring Boot includes a Maven plugin that can package the project     
as an executable jar. Add the plugin to your <plugins> section if
you want to use it, as shown in the following example:

Spring Boot引入了一个Maven的插件,可以打包工程,使之成为一个可执行jar。如果您想使用它的话,增加该插件到部分。如下展示的示例:

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
1
2
3
If you use the Spring Boot starter parent pom, you need     
to add only the plugin. There is no need to configure it
unless you want to change the settings defined in the parent.

如果您使用父POM的方式,您仅仅只需要增加这个插件就可以了。不需要配置它,除非您想改变父POM定义的配置。

分享到

SpringBoot官方文档翻译(十):创建一个可执行jar包

11.5 Creating an Executable Jar(运行示例)

1
2
3
4
5
We finish our example by creating a completely self-contained     
executable jar file that we could run in production. Executable
jars (sometimes called “fat jars”) are archives containing your
compiled classes along with all of the jar dependencies that your
code needs to run.

我们通过创建一个完全独立的可执行JAR文件来完成我们的示例,我们可以在生产中运行它。可执行jars(有时候也叫做“重量级jars”)是包含了您自身编译的类和其所依赖的所有jar包的一个整合归档包。

Executable jars and Java

1
2
3
4
5
6
7
8
9
10
11
Java does not provide a standard way to load nested jar files (jar     
files that are themselves contained within a jar). This can be
problematic if you are looking to distribute a self-contained application.
To solve this problem, many developers use “uber” jars. An uber
jar packages all the classes from all the application’s dependencies
into a single archive. The problem with this approach is that it
becomes hard to see which libraries are in your application.
It can also be problematic if the same filename is used (but
with different content) in multiple jars.
Spring Boot takes a different approach and lets you actually
nest jars directly.

Java并不提供一个标准的方式去嵌套jar文件(jar文件本身又包含另一个jar)。这将成为一个阻碍,如果您打算发布一个独立运行的jar应用。
为了解决这个问题,很多开发者使用“uber”包。一个“uber”包根据应用的依赖关系打包了所有的类到一个单独的归档中。采用这种途径打包之后产生的另一个问题是,您无法知道在您的应用中有哪些库。
这还产生一个新的问题就是一些同名的文件会被应用到多个不同的(但包含不同的内容)jars当中。
Spring Boot 采用了一个不同的方式让您可以直接嵌套jars包。

1
2
3
To create an executable jar, we need to add the     
spring-boot-maven-plugin to our pom.xml. To do so,
insert the following lines just below the dependenciessection:

创建一个可执行jar,我们需要增减一个spring-boot-maven-plugin到pom文件中。可以这样做,插入下面的配置行到依赖关系部分下面。

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
1
2
3
4
The spring-boot-starter-parent POM includes <executions>     
configuration to bind the repackage goal. If you do not
use the parent POM, you need to declare this configuration
yourself. See the plugin documentation for details.

spring-boot-starter-parent的pom文件包含配置,可以绑定执行repackage对象。如果您不使用父POM,您需要自己声明这个配置。您可以在plugin的文档中得到更为详细的信息(https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/maven-plugin/usage.html)

1
Save your pom.xml and run mvn package from the command line, as follows:

保存您的pom.xml,在命令行中运行mvn package,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ mvn package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.1.0.BUILD-SNAPSHOT:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

1
2
3
4
If you look in the target directory, you should see     
myproject-0.0.1-SNAPSHOT.jar. The file should be around
10 MB in size. If you want to peek inside, you can use 
jar tvf, as follows:

如果您在target目录下查看,你将会看到myproject-0.0.1-SNAPSHOT.jar。这个文件大概10M左右的样子。如果您想一窥内部构造,您可以使用 jar tvf命令,如下:

1
$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar
1
2
3
4
You should also see a much smaller file named myproject-0.0.1-    
SNAPSHOT.jar.original in the target directory. This is the original
jar file that Maven created before it was repackaged by Spring Boot.
To run that application, use the java -jar command, as follows:

您应该同样的会看到一个比较小的名称为myproject-0.0.1-SNAPSHOT.jar.original的文件在target目录下。这是maven在Spring Boot进行repackaged之前创建的原版的jar文件。运行这个应用,使用java -jar命令,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.0.BUILD-SNAPSHOT)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)
1
As before, to exit the application, press ctrl-c.

跟之前一样,如果想退出应用,按ctrl+c

12. What to Read Next(接下去阅读什么)

1
2
3
4
5
Hopefully, this section provided some of the Spring Boot basics     
and got you on your way to writing your own applications. If you
are a task-oriented type of developer, you might want to jump over to spring.io and check out some of the getting started guides that
solve specific “How do I do that with Spring?” problems. We also
have Spring Boot-specific “How-to” reference documentation.

希望,本节提供了一些Spring Boot的基础知识和能帮助您以您自己的方式编写自己的应用程序。
如果您是一个面向任务的开发人员类型,您可能想跳到spring.io并查看一些入门指南解决具体的“我怎样用Spring做这件事”的问题。 我们也具有特定于Spring Boot的“操作方法”参考文档。

1
2
3
The Spring Boot repository also has a bunch of samples you can run.     
The samples are independent of the rest of the code (that is, you
do not need to build the rest to run or use the samples).

Spring Boot存储库还有一堆你可以运行的样本。样本与代码的其余部分无关(即,您
无需要构建其余的代码去运行或使用样本)

1
2
3
Otherwise, the next logical step is to read Part III, “Using Spring     
Boot”. If you are really impatient, you could also jump ahead and
read about Spring Boot features.

除此之外,下一个合乎逻辑的步骤是阅读第三部分,“使用Spring Boot”。如果您真的不耐烦,您可以跳过此章节,阅读Spring Boot的功能部分。

分享到

SpringBoot官方文档翻译(九):运行示例

11.4 Running the Example(运行示例)

1
2
3
4
5
At this point, your application should work. Since you used the     
spring-boot-starter-parent POM, you have a useful run goal that you
can use to start the application. Type mvn spring-boot:run from the
root project directory to start the application. You should see output
similar to the following:

此时,您的应用程序应该可以工作了。由于使用了spring-boot-starter-parent POM,所以您有一个可用的运行目标,可以用来启动应用程序。在工程的根木兰路下输入mvn spring-boot:run启动应用。您应该看到类似于以下的输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
$ mvn spring-boot:run

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.0.BUILD-SNAPSHOT)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)

1
2
If you open a web browser to localhost:8080, you should see     
the following output:

如果您打开一个web浏览器输入localhost:8080,您将会看到如下的输出:

1
Hello World!
1
To gracefully exit the application, press ctrl-c.

优雅退出请按ctrl+c

分享到

SpringBoot官方文档翻译(八):开始写代码

11.3 Writing the Code(开始写代码)

1
2
3
4
To finish our application, we need to create a single Java file.     
By default, Maven compiles sources from src/main/java, so you need
to create that folder structure and then add a file named 
src/main/java/Example.java to contain the following code:

为了完成我们的应用,我们需要创建一个单独的java文件夹。默认情况下,maven从src/main/java中编译源码,因此,您需要创建一个类似于此的文件结构目录并加入您的示例类src/main/java/Example.java并包含以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

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

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

}
1
2
Although there is not much code here, quite a lot is going on.     
We step through the important parts in the next few sections.

尽管并没有多少代码,但很多事情静静的发生了。我们将在接下来的章节,带您一步一步解开它的神秘面纱。

11.3.1 The @RestController and @RequestMapping Annotations

1
2
3
4
5
The first annotation on our Example class is @RestController.     
This is known as a stereotype annotation. It provides hints
for people reading the code and for Spring that the class plays
a specific role. In this case, our class is a web @Controller,
so Spring considers it when handling incoming web requests.

在我们Example类的第一个注解是@RestController。这被认为是一个刻板的注解。它为大家提供了直接的提示,并且告诉Spring容器,被注解的这个类扮演了一个特殊的角色。在这个例子李,我们的类是一个web类型的@Controller,所以Spring会注意到这点,并将web请求交给该类来处理。

1
2
3
4
The @RequestMapping annotation provides “routing” information.     
It tells Spring that any HTTP request with the / path should be
mapped to the home method. The@RestController annotation tells
Spring to render the resulting string directly back to the caller.

@RequestMapping注解提供了“路由”信息。它告诉Sring,任何的HTTP以/结尾的请求需要映射到home方法上。@RestController注解告诉Spring将结果字符串直接返回给调用方。

1
2
3
The @RestController and @RequestMapping annotations are Spring     
MVC annotations. (They are not specific to Spring Boot.) See
the MVC sectionin the Spring Reference Documentation for more details.

@RestController和@RequestMapping这两个注解是Spring MVC的注解,并非专门为Spring Boot提供的。您可以到Spring官方文档的MVC相关的章节去获取更多的信息。

11.3.2 The @EnableAutoConfiguration Annotation

1
2
3
4
5
6
The second class-level annotation is @EnableAutoConfiguration.     
This annotation tells Spring Boot to “guess” how you want to
configure Spring, based on the jar dependencies that you have added.
Since spring-boot-starter-web added Tomcat and Spring MVC,
the auto-configuration assumes that you are developing a web
application and sets up Spring accordingly.

第二个类级别注解@EnableAutoConfiguration,这个注解告诉Spring Boot 去“猜”您是想怎样配置Spring,基于您已经添加的jar包依赖。因为spring-boot-starter-web包含了Tomcat和Spring MVC,auto-configuration自动配置会推断您想开发一个web应用并据此设定Spring相关配置。

1
2
3
4
5
Starters and Auto-Configuration
Auto-configuration is designed to work well with “Starters”, but
the two concepts are not directly tied. You are free to pick and
choose jar dependencies outside of the starters. Spring Boot still
does its best to auto-configure your application.

“Starters”和“Auto-Configuration”
自动配置的设计是为了更好的配合“Starters”运作,但是两个概念并不直接相关。您可以自由的挑选不在“Starters”中的jar依赖。Spring Boot依然尽最大努力为您的应用做自动配置。

11.3.3 The “main” Method (”main“方法)

1
2
3
4
5
6
7
8
9
The final part of our application is the main method. This is     
just a standard method that follows the Java convention for an
application entry point. Our main method delegates to Spring
Boot’s SpringApplication class by calling run. SpringApplication 
bootstraps our application, starting Spring, which, in turn,
starts the auto-configured Tomcat web server. We need to pass 
Example.class as an argument to the run method to tell 
SpringApplication which is the primary Spring component. The 
args array is also passed through to expose any command-line arguments.

本节的最后一部分介绍我们应用的”main“方法。这只是遵循Java约定的标准方法应用程序入口点。
我们的main方法会调用给Spring Boot的SpringApplication类的run方法。SpringApplication引导我们的应用程序,从Spring开始,启动自动配置的Tomcat Web服务器。我们需要将Example.class作为run方法的一个参数,去通知SpringApplication,这是Spring的主要组件。该参数数组同样可以通过任何暴露的命令行参数进行传递。

分享到