Spring Boot文档阅读

时间:2022-05-04
本文章向大家介绍Spring Boot文档阅读,主要内容包括原因之初、一、Start--HelloWorld、1.2编写pom---11.1 Creating the POM、1.3编写代码---11.3 Writing the code、1.4运行---11.4 Running the example、二要点记录、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

原因之初

最初习惯百度各种博客教程,然后跟着操作,因为觉得跟着别人走过的路走可以少走很多弯路,省时间。然而,很多博客的内容并不够完整,甚至错误,看多了的博客甚至有千篇一律的感觉。此外,博客毕竟是记载博主的心路历程而不是自己,就像我的博客,从来都是当做记事本来写的,条例和思路基本上是根据遇到的问题记录下来的,绝对不会钻研一下如何发布科普文章。

新入职的公司需要英语环境,觉得有必要读英语的东西,看Google出来的文章辨别质量难度更甚,还是看官方文档吧。最初看gradle,科普gradle的基本知识,然而并没有使我更了解gradle,原因是我把它当做速食快餐一样的浏览,但英文理解能力却没有跟上,就会似懂非懂。急于求成啊!后来发现需要Spring Boot方面的知识,只好硬着头皮去看。必须要看懂。开始看的很慢,有道词典的单词本内容一下就扩充了。但后来发现还是蛮有趣的。所以,耐心,坚持,专注!

参考:Spring Boot Documentation

一、Start--HelloWorld

1.1环境搭建

需要将maven3+,java7+,Spring Boot CLI加入系统变量。方法都是将_HOMEbin放入path变量中。

资源:

环境搭建成功:

C:UsersAdministrator>javac -version
javac 1.8.0_60

C:UsersAdministrator>mvn -version
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T19:57:3
7+08:00)
Maven home: D:Javaapache-maven-3.3.3bin..
Java version: 1.8.0_60, vendor: Oracle Corporation
Java home: D:Javajdk1.8.0_60jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 7", version: "6.1", arch: "amd64", family: "dos"

C:UsersAdministrator>spring --version
Spring CLI v1.4.0.BUILD-SNAPSHOT
C:UsersAdministrator>

1.2编写pom---11.1 Creating the POM

创建一个pom.xml文件,放到非中文路径下。建议创建目录myproject,目录下创建文件pom.xml.编辑器建议使用sublime或visual studio code等。

<?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>1.4.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>http://repo.spring.io/snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>
</project>
  1. cmd进入当前目录,mvn package打包。如果本地没有maven jar,需要时间下载。
  2. pom中parent包含了springboot需要的各种jar。下面需要添加一个web starter的依赖,放置于parent节点下。
  3. Let’s edit our pom.xml and add the spring-boot-starter-web dependency just below the parent section: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>

1.3编写代码---11.3 Writing the code

首先,本测试用例是基于maven的,所以要清楚了解maven的项目结构。在pom.xml当前目录创建 src/main/java/Example.java:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
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.4运行---11.4 Running the example

在cmd命令行输入mvn spring-boot:run。下载完jar后,出现如下banner,即运行成功。在浏览器输入:localhost:8080即可。结束:ctrl-c

$ mvn spring-boot:run

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

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

Hello World!

To gracefully exit the application hit ctrl-c.

二要点记录

记录到印象笔记中:https://www.evernote.com/shard/s743/sh/cd6277bb-c0a8-41a6-a836-a99fdaeaa5f2/1a8be7703396fb83

Spring Boot Doc

2016年4月21日

9:13

  • 基础配置 
  • 继承官方pom,省心配置: 
  • <!-- Inherit defaults from Spring Boot --> 
  • <parent> 
  •     <groupId>org.springframework.boot</groupId> 
  •     <artifactId>spring-boot-starter-parent</artifactId> 
  •     <version>1.4.0.BUILD-SNAPSHOT</version> 
  • </parent> 
  • 这样会得到这些依赖:https://github.com/spring-projects/spring-boot/blob/master/spring-boot-dependencies/pom.xml 
  • 13.2.2Using Spring Boot without the parent POM 
  • 如果你想要自定义version,可以override ther properties: 
  • <properties> 
  •     <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version> 
  • </properties> 
  • 如果你不愿意inherit spring-boot-starter-parent,可以使用dependencyManagement,scope为import 
  • If you don’t want to use thespring-boot-starter-parent, you can still keep the benefit of the dependency management (but not the plugin management) by using ascope=importdependency: 
  • <dependencyManagement> 
  •      <dependencies> 
  •         <dependency> 
  •             <!-- Import dependency management from Spring Boot --> 
  •             <groupId>org.springframework.boot</groupId> 
  •             <artifactId>spring-boot-dependencies</artifactId> 
  •             <version>1.4.0.BUILD-SNAPSHOT</version> 
  •             <type>pom</type> 
  •             <scope>import</scope> 
  •         </dependency> 
  •     </dependencies> 
  • </dependencyManagement> 
  • 这时,你如果想要自定义某个dependency的version就不能使用properties来override了。你可以将想要自定义的version放置于spring-boot-dependecies之前。 
  • you’d need to add an entry in thedependencyManagementof your projectbeforethespring-boot-dependenciesentry. For instance, to upgrade to another Spring Data release train you’d add the following to yourpom.xml. 
  • <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> 
  •             <scope>import</scope> 
  •             <type>pom</type> 
  •         </dependency> 
  •         <dependency> 
  •             <groupId>org.springframework.boot</groupId> 
  •             <artifactId>spring-boot-dependencies</artifactId> 
  •             <version>1.4.0.BUILD-SNAPSHOT</version> 
  •             <type>pom</type> 
  •             <scope>import</scope> 
  •         </dependency> 
  •     </dependencies> 
  • </dependencyManagement> 
  • 13.2.3Changing the Java version 
  • 自定义java version 
  • Thespring-boot-starter-parentchooses fairly conservative Java compatibility. If you want to follow our recommendation and use a later Java version you can add ajava.versionproperty: 
  • <properties> 
  •     <java.version>1.8</java.version> 
  • </properties> 
  • 13.2.4Using the Spring Boot Maven plugin 
  • 更省心的配置,使用maven  palugin将项目package成一个executable jar,可以直接使用java -jar target.jar运行。 
  • Spring Boot includes aMaven pluginthat can package the project as an executable jar. Add the plugin to your<plugins>section if you want to use it: 
  • <build> 
  •     <plugins> 
  •         <plugin> 
  •             <groupId>org.springframework.boot</groupId> 
  •             <artifactId>spring-boot-maven-plugin</artifactId> 
  •         </plugin> 
  •     </plugins> 
  • </build> 
  • 14.2Locating the main application class---项目使用注解配置 
  • 在项目中用一个main class作为项目入口,使用 
    • @EnableAutoConfiguration:  serche for @Entity 
    • @ComponentScan:  不用配置basePackage, 
  • All of your application components (@Component,@Service,@Repository,@Controlleretc.) will be automatically registered as Spring Beans. 
    • @SpringBootApplication: 这个注解的class要放置于root package,same as @Configuration @EnableAutoConfiguration @ComponentScan 
    • @Configuration:  配置文件声明,使用enable*来代替xml配置 
    • @AutoWired:  自动注入,声明的方法上,声明在变量上应该也可以。 
  • We generally recommend that you locate your main application class in a root package above other classes. The @EnableAutoConfiguration 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 @EnableAutoConfiguration annotated class will be used to search for@Entityitems.
  • Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. You can also use the @SpringBootApplication annotation if your main class is in the root package.
  • Here is a typical layout: 
  • com 
  • +- example 
  •      +- myproject 
  •          +- Application.java 
  •          | 
  •          +- domain 
  •          |   +- Customer.java 
  •          |   +- CustomerRepository.java 
  •          | 
  •          +- service 
  •          |   +- CustomerService.java 
  •          | 
  •          +- web 
  •              +- CustomerController.java 
  • TheApplication.javafile would declare themainmethod, along with the basic@Configuration. 
  • package com.example.myproject; 
  • import org.springframework.boot.SpringApplication; 
  • import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 
  • import org.springframework.context.annotation.ComponentScan; 
  • import org.springframework.context.annotation.Configuration; 
  • @Configuration 
  • @EnableAutoConfiguration 
  • @ComponentScan 
  • public class Application { 
  • public static void main(String[] args) { 
  •         SpringApplication.run(Application.class, args); 
  •     } 
  • 15.Configuration classes 
  • Spring Boot favors Java-based configuration. Although it is possible to callSpringApplication.run()with an XML source, we generally recommend that your primary source is a@Configurationclass. Usually the class that defines themainmethod is also a good candidate as the primary@Configuration. 
  • Spring Boot支持java配置。尽管可以使用SpringApplication.run()调用xml,但我们通常推荐你的主要配置文件是一个@Configuration类。通常main方法是主要的设置类。 
  • 15.1 Importing additional configuration classes 
  • You don’t need to 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类。 
  • 15.2 Importing XML configuration 
  • If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an additional@ImportResource annotation to load XML configuration files. 
  • 如果你必须要使用xml配置,我们推荐你仍然通过@Configuration类启动。你可以使用额外的@ImportResource注解来加载xml配置文件。 
  • 16.Auto-configuration----@EnableAutoConfiguration或@SpgingBootApplication只使用一次 
  • Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, IfHSQLDBis on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database. 
  • Spring Boot自动配置试图去根据你的jar依赖来自动配置你的应用。比如,如果HSQLDB在你的classpath,你不用手动配置任何database connection beans,spring会自动配置一个在内存中的database。
  • You need to opt-in to auto-configuration by adding the@EnableAutoConfigurationor@SpringBootApplicationannotations to one of your@Configurationclasses. 
  • 你必须通过添加@EnableAutoConfiguration或者@SpringBootApplication注解到你的其中一个@Configuration注解类中,来实现自动配置。 

You should only ever add one@EnableAutoConfigurationannotation. We generally recommend that you add it to your primary@Configurationclass.

你必须只添加一个@EnableAutoConfiguration注解,我们推荐你添加到你的主配置类。

  • 16.1 Gradually replacing auto-configuration 
  • Auto-configuration is noninvasive, 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 will back away. 
  • If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug switch. This will enables debug logs for a selection of core loggers and log an auto-configuration report to the console. 
  • 自动配置是非侵害的,你可以在任何地方开始定义你自己的配置来替换指定的自动配置部分。比如,如果你添加了你自己的DataSource bean,默认的嵌入的database支持就会回退。 
  • 如果你需要找出当前有哪些自动配置已经应用了,或者为什么应用,通过参数 --debug来启动你的应用。这样会允许log报告自动配置信息 
  • 16.2Disabling specific auto-configuration---去掉一些你不想要自动配置的东西 
  • If you find that specific auto-configure classes are being applied that you don’t want, you can use the exclude attribute of@EnableAutoConfigurationto disable them. 
  • 如果你发现有些自动配置你不想要,你可以使用@EnableAutoConfiguration注解的参数exclude来禁用。 
  • import org.springframework.boot.autoconfigure.*; 
  • import org.springframework.boot.autoconfigure.jdbc.*; 
  • import org.springframework.context.annotation.*; 
  • @Configuration 
  • @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 
  • public class MyConfiguration { 
  • If the class is not on the classpath, you can use theexcludeNameattribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude via thespring.autoconfigure.excludeproperty. 
  • 如果class没有在classpath中,你可以使用参数excludeName来指定全称,你也可以通过属性配置来禁用。 
  • 17. Spring Beans and dependency injection---spring bean和依赖注入 
  • 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, in combination with @Autowired constructor injection works well. 
  • 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.) will be automatically registered as Spring Beans. 
  • 你可以使用任何标准的springframework技术来定义你的bean和依赖注入。简单的说,我们通常通过@ComponentScan来找到你的beans,再与@Autowired构造器注入结合。 @Atutowired注入原则:先根据bean id注入,若没找到bean id再根据bean type注册。
  • 如果按照要求搭建项目结构,@ComponentScan会注册所有的组件。 
  • Here is an example @Service Bean that uses constructor injection to obtain a required RiskAssessor bean. 
  • 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;
  • }  
  •  // ...  

Notice how using constructor injection allows the riskAssessor field to be marked as final, indicating that it cannot be subsequently changed.

注意,被注入的字段是final的,即不可以再修改了。

  • 18.Using the @SpringBootApplication annotation---使用注解@SpringBootApplication 
  • Many Spring Boot developers always have their main class annotated with@Configuration,@EnableAutoConfigurationand@ComponentScan. Since these annotations are so frequently used together (especially if you follow thebest practicesabove), Spring Boot provides a convenient@SpringBootApplicationalternative. 
  • The@SpringBootApplicationannotation is equivalent to using@Configuration,@EnableAutoConfigurationand@ComponentScanwith their default attributes: 
  • @SpringBootApplication== @Configuration,@EnableAutoConfigurationand@ComponentScan,但仅仅是默认配置,如果需要自定义则需要另外配置。 
  • package com.example.myproject; 
  • import org.springframework.boot.SpringApplication; 
  • import org.springframework.boot.autoconfigure.SpringBootApplication; 
  • @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan 
  • public class Application { 
  • public static void main(String[] args) { 
  •         SpringApplication.run(Application.class, args); 
  •     } 
  • 19. Running your application
  • One of the biggest advantages of packaging your application as jar and using an embedded HTTP server is that you can run your application as you would any other. Debugging Spring Boot applications is also easy; you don’t need any special IDE plugins or extensions.
  • 其中一个最大的好出就是将你的应用打包成jar,并且使用一个自定义嵌入的http server。

This section only covers jar based packaging, If you choose to package your application as a war file you should refer to your server and IDE documentation.

  • 19.1 Running from an IDE
  • You can run a Spring Boot application from your IDE as a simple Java application, however, first you will need to import your project. Import steps will vary depending on your IDE and build system. Most IDEs can import Maven projects directly, for example Eclipse users can select Import…​ → Existing Maven Projects from theFile menu.
  • If you can’t directly import your project into your IDE, you may be able to generate IDE metadata using a build plugin. Maven includes plugins for Eclipse and IDEA; Gradle offers plugins for various IDEs.
  • 可以导入maven项目到ide中开发。

If you accidentally run a web application twice you will see a “Port already in use” error. STS users can use the Relaunch button rather than Run to ensure that any existing instance is closed.

  • 19.2 Running as a packaged application
  • If you use the Spring Boot Maven or Gradle plugins to create an executable jar you can run your application using java -jar. For example:
  • 如果你使用spring boot maven或者gradle plugin来创建一个executable jar。你可以直接运行:
  • $ java -jar target/myproject-0.0.1-SNAPSHOT.jar
  • It is also possible to run a packaged application with remote debugging support enabled. This allows you to attach a debugger to your packaged application:
  • $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n        -jar target/myproject-0.0.1-SNAPSHOT.jar
  • 19.3 Using the Maven plugin
  • The Spring Boot Maven plugin includes a run goal which can be used to quickly compile and run your application. Applications run in an exploded form just like in your IDE.
  • 也可以:
  • $ mvn spring-boot:run
  • You might also want to use the useful operating system environment variable:
  • $ export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom
  • (The “egd” setting is to speed up Tomcat startup by giving it a faster source of entropy for session keys.)
  • 20. Developer tools
  • Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant. The spring-boot-devtools module can be included in any project to provide additional development-time features. To include devtools support, simply add the module dependency to your build:
  • 可以添加developer tools来方便开发。
  • Maven. 
  • <dependencies>     <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-devtools</artifactId>         <optional>true</optional>     </dependency> </dependencies>
  • Developer tools可以实现热加载,热部署,以及关闭和远程热部署。详情可仔细查看文档,此处略过。
  • 23.6 Accessing application arguments---参数注入
  • If you need to access the application arguments that were passed to SpringApplication.run(…​) you can inject aorg.springframework.boot.ApplicationArguments bean.
  • 如果你需要接收一个application参数,可以用@Autowired自动注入:
  • The ApplicationArguments interface provides access to both the raw String[] arguments as well as parsed option and non-option arguments:
  • import org.springframework.boot.* import org.springframework.beans.factory.annotation.* import org.springframework.stereotype.*
  • @Component public class MyBean {
  • @Autowired     public MyBean(ApplicationArguments args) {         boolean debug = args.containsOption("debug");         List<String> files = args.getNonOptionArgs();         // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]     }
  • }

Spring Boot will also register a CommandLinePropertySource with the Spring Environment. This allows you to also inject single application arguments using the @Value annotation.

  • 23.7 Using the ApplicationRunner or CommandLineRunner---编写项目启动后运行的代码
  • If you need to run some specific code once the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces. Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…​) completes.
  • 如果你需要在SpringApplication开始之后运行一些代码,可以实现ApplicationRunner 或者CommandLineRunner 接口。额外的实现org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order annotation可以设置运行顺序。
  • The CommandLineRunner interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner uses theApplicationArguments interface discussed above.
  • import org.springframework.boot.* import org.springframework.stereotype.*
  • @Component
  • @Order(1)
  • public class MyBean implements CommandLineRunner {
  • public void run(String... args) {         // Do something...     }
  • }
  • You can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation if several CommandLineRunner or ApplicationRunner beans are defined that must be called in a specific order.
  • http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config
  • 24. Externalized Configuration--加载属性配置
  • Spring Boot allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration. Property values can be injected directly into your beans using the @Valueannotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties.
  • Spring Boot提供了多种获取外置属性的方式:
  • Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values, properties are considered in the following order:
    1. Command line arguments.
    2. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
    3. JNDI attributes from java:comp/env.
    4. Java System properties (System.getProperties()).
    5. OS environment variables.
    6. A RandomValuePropertySource that only has properties in random.*.
    7. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
    8. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
    9. Application properties outside of your packaged jar (application.properties and YAML variants).
    10. Application properties packaged inside your jar (application.properties and YAML variants).
    11. @PropertySource annotations on your @Configuration classes.
    12. Default properties (specified using SpringApplication.setDefaultProperties).
  • To provide a concrete example, suppose you develop a @Component that uses a name property:
  • import org.springframework.stereotype.* import org.springframework.beans.factory.annotation.*
  • @Component public class MyBean {
  • @Value("${name}") private String name;
  • // ...
  • }
  • On your application classpath (e.g. inside your jar) you can have an application.properties that provides a sensible default property value for name. When running in a new environment, an application.properties can be provided outside of your jar that overrides the name; and for one-off testing, you can launch with a specific command line switch (e.g. java -jar app.jar --name="Spring").

The SPRING_APPLICATION_JSON properties can be supplied on the command line with an environment variable. For example in a UN*X shell: $ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar In this example you will end up with foo.bar=spam in the Spring Environment. You can also supply the JSON as spring.application.json in a System variable: $ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar or command line argument: $ java -jar myapp.jar --spring.application.json='{"foo":"bar"}' or as a JNDI variable java:comp/env/spring.application.json.

  • 24.1 Configuring random values
  • The RandomValuePropertySource is useful for injecting random values (e.g. into secrets or test cases). It can produce integers, longs or strings, e.g.
  • 可以使用random函数
  • my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
  • The random.int* syntax is OPEN value (,max) CLOSE where the OPEN,CLOSE are any character and value,max are integers. If max is provided then value is the minimum value and max is the maximum (exclusive).
  • 24.2 Accessing command line properties
  • By default SpringApplication will convert any command line option arguments (starting with ‘--’, e.g. --server.port=9000) to a property and add it to the SpringEnvironment. As mentioned above, command line properties always take precedence over other property sources.
  • If you don’t want command line properties to be added to the Environment you can disable them usingSpringApplication.setAddCommandLineProperties(false).
  • 命令行参数优先级最高。
  • 24.3 Application property files
  • SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
    1. A /config subdirectory of the current directory.
    2. The current directory
    3. A classpath /config package
    4. The classpath root
  • The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
  • 优先级从1到4依次降低

You can also use YAML ('.yml') files as an alternative to '.properties'.

  • 设置属性文件位置:
  • If you don’t like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property. You can also refer to an explicit location using the spring.config.location environment property (comma-separated list of directory locations, or file paths).
  • $ java -jar myproject.jar --spring.config.name=myproject
  • or
  • $ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

spring.config.name and spring.config.location are used very early to determine which files have to be loaded so they have to be defined as an environment property (typically OS env, system property or command line argument).

  • If spring.config.location contains directories (as opposed to files) they should end in / (and will be appended with the names generated fromspring.config.name before being loaded, including profile-specific file names). Files specified in spring.config.location are used as-is, with no support for profile-specific variants, and will be overridden by any profile-specific properties.
  • The default search path classpath:,classpath:/config,file:,file:config/ is always used, irrespective of the value of spring.config.location. This search path is ordered from lowest to highest precedence (file:config/ wins). If you do specify your own locations, they take precedence over all of the default locations and use the same lowest to highest precedence ordering. In that way you can set up default values for your application in application.properties (or whatever other basename you choose with spring.config.name) and override it at runtime with a different file, keeping the defaults.
  • 默认位置加载属性文件为最低优先级,自定义的优先级高。

If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (e.g. SPRING_CONFIG_NAME instead of spring.config.name).

If you are running in a container then JNDI properties (in java:comp/env) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties.

  • 24.4 Profile-specific properties
  • In addition to application.properties files, profile-specific properties can also be defined using the naming convention application-{profile}.properties. The Environment  has a set of default profiles (by default [default]) which are used if no active profiles are set (i.e. if no profiles are explicitly activated then properties from application-default.properties are loaded).
  • Profile-specific properties are loaded from the same locations as standard application.properties, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.
  • If several profiles are specified, a last wins strategy applies. For example, profiles specified by the spring.profiles.active property are added after those configured via the SpringApplication API and therefore take precedence.
  • 当application.propertie中未声明当前属性,则从application-defualt.properties中寻找。

If you have specified any files in spring.config.location, profile-specific variants of those files will not be considered. Use directories in`spring.config.location` if you also want to also use profile-specific properties.

  • 24.5 Placeholders in properties
  • The values in application.properties are filtered through the existing Environment when they are used so you can refer back to previously defined values (e.g. from System properties).
  • 属性文件中可以调用之前声明的属性:
  • app.name=MyApp app.description=${app.name} is a Spring Boot application

You can also use this technique to create ‘short’ variants of existing Spring Boot properties. See the Section 70.4, “Use ‘short’ command line arguments”how-to for details.

  • 24.6 Using YAML instead of Properties
  • YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. The SpringApplication class will automatically support YAML as an alternative to properties whenever you have the SnakeYAML library on your classpath.
  • 使用YAML,需要snakeyaml.jar,starter自动加载。

If you use ‘starter POMs’ SnakeYAML will be automatically provided via spring-boot-starter.

  • 24.6.1 Loading YAML
  • yml文件格式:
    • ": "冒号空格声明一个变量
    • "- "短横空格声明一个String
    • 同一层的属性前的缩进必须一致
    • "---"用来分割一组配置
  • Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Propertiesand the YamlMapFactoryBean will load YAML as a Map.
  • For example, the following YAML document:
  • environments:     dev:         url: http://dev.bar.com         name: Developer Setup     prod:         url: http://foo.bar.com         name: My Cool App
  • Would be transformed into these properties:
  • environments.dev.url=http://dev.bar.com environments.dev.name=Developer Setup environments.prod.url=http://foo.bar.com environments.prod.name=My Cool App
  • YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
  • my:    servers:        - dev.bar.com        - foo.bar.com
  • Would be transformed into these properties:
  • my.servers[0]=dev.bar.com my.servers[1]=foo.bar.com
  • To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties does) you need to have a property in the target bean of type java.util.List (or Set) and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above
  • @ConfigurationProperties(prefix="my") public class Config {
  • private List<String> servers = new ArrayList<String>();
  • public List<String> getServers() { return this.servers;     } }
  • 24.6.4 YAML shortcomings
  • YAML files can’t be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file.
  • YAML files不可以通过@PropertySource注解加载。
  • 24.7 Type-safe Configuration Properties
  • Using the @Value("${property}") annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that allows strongly typed beans to govern and validate the configuration of your application. For example:
  • @Value有时候太笨重,尤其多重配置的时候,这时候可以使用@ConfigurationProperties
  • @Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings {
  • private String username;
  • private InetAddress remoteAddress;
  • // ... getters and setters
  • }

getter和setter方法是明智的,因为bind是通过标准java bean属性描述的,就像springMVC.他们被委托给不可变类型或者直接强制转换String的。只要他们初始化,maps,collections,arrays需要getter。而setter是不必须的,因为他们可以被绑定改变。如果有setter,maps,collections,arrays会被创建。Maps,collections仅仅通过getter可以被扩展,然而arrays需要一个setter。嵌套的pojo属性可以被创建,如果他们有默认的构造器。

The getters and setters are advisable, since binding is via standard Java Beans property descriptors, just like in Spring MVC. They are mandatory for immutable types or those that are directly coercible from String. As long as they are initialized, maps, collections, and arrays need a getter but not necessarily a setter since they can be mutated by the binder. If there is a setter, Maps, collections, and arrays can be created. Maps and collections can be expanded with only a getter, whereas arrays require a setter. Nested POJO properties can also be created (so a setter is not mandatory) if they have a default constructor, or a constructor accepting a single value that can be coerced from String. Some people use Project Lombok to add getters and setters automatically.

Contrary to @Value, SpEL expressions are not evaluated prior to injecting a value in the relevant @ConfigurationProperties bean.

  • 24.7.1 Third-party configuration
  • As well as using @ConfigurationProperties to annotate a class, you can also use it on @Bean methods. This can be particularly useful when you want to bind properties to third-party components that are outside of your control.
  • @Bean注解可以将一个pojo注册成一个bean,由Spring container来管理。这里要注意getter方法会一起json解析。
  • To configure a bean from the Environment properties, add @ConfigurationProperties to its bean registration:
  • @ConfigurationProperties(prefix = "foo") @Bean public FooComponent fooComponent() {     ... }
  • Any property defined with the foo prefix will be mapped onto that FooComponent bean in a similar manner as the ConnectionSettings example above.
  • 来自 <http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config>

已使用 Microsoft OneNote 2016 创建。