spring boot properties【翻译】

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

 

综述

可以通过使用properties文件,yaml文件,环境变量以及命令行参数,来传递参数。属性值可以通过 @ConfigurationProperties 或者Spring 的 Environment抽象获得,并使用@Value注解直接映射到bean的属性中。

     SpringBoot 使用属性覆盖顺序:

     

  1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
  2. @TestPropertySource annotations on your tests.
  3. @SpringBootTest#properties annotation attribute on your tests.
  4. Command line arguments.
  5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
  6. ServletConfig init parameters.
  7. ServletContext init parameters.
  8. JNDI attributes from java:comp/env.
  9. Java System properties (System.getProperties()).
  10. OS environment variables.
  11. A RandomValuePropertySource that only has properties in random.*.
  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  14. Application properties outside of your packaged jar (application.properties and YAML variants).
  15. Application properties packaged inside your jar (application.properties and YAML variants).
  16. @PropertySource annotations on your @Configuration classes.
  17. Default properties (specified using SpringApplication.setDefaultProperties).

 

这里给出了一个特别注释: SPRING_APPLICATION_JSON的配置方法。

  1.     类Linux的shell方式:
    $ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar
  2. 系统变量:
    $ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar
  3. 命令行变量:
    $ java -jar myapp.jar --spring.application.json='{"foo":"bar"}'
  4. JNDI变量: java:comp/env/spring.application.json

 

配置随机变量

RandomValuePropertySource可以随机生成 integers, longs, uuids or strings

 

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
 

 

命令行配置

默认情况下, SpringApplication会将命令行配置(以--开头,比如 --server.port=9000)添加到Spring的环境中。

可以通过 SpringApplication.setAddCommandLineProperties(false)关闭此功能。

 

 

Application配置文件

Spring会自动加载 application.properties配置文件。扫描的路径包括:

  1. 当前路径下的 /config文件夹下
  2. 当前路径下
  3. classpath的/config文件夹下
  4. classpath的根目录

     yaml文件也是同理。

 如果不喜欢默认的application.properties,也可以通过配置实现其他的设定:

  1.     自定义 spring.config.name:
    $ java -jar myproject.jar --spring.config.name=myproject
  2. 自定义 spring.config.location

          $ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

     默认的配置文件搜索路径: classpath:,classpath:/config,file:,file:config/(file:config/ 的优先级最高

 

 

Profile-specific properties

可以通过制定名称来实现配置文件覆盖。 application-{profile}.properties。其中profile通过 spring.profiles.active指定。

 

 

Placeholders in properties

application.properties中的变量可以在之后的配置中使用。

例如:

app.name=MyApp
app.description=${app.name} is a Spring Boot application
 

 

 

Using YAML instead of Properties

yaml为一种json格式,可以和properties相互转换。这里不涉及,所以不翻译了。

 

 

Type-safe Configuration Properties

@Value("${property}")有的时候使用起来很笨重,尤其是有多个属性,或者属性有层次关系。spring提供了一种额外的方式支持多层次,多属性情形。

两种实现方式:

  1.     
    EnableConfigurationProperties中指定配置的class

          

     首先注册配置文件的class:

     

@Configuration

@EnableConfigurationProperties(FooProperties.class)

public class MyConfiguration {

}

 

     然后通过ConfigurationProperties注解配置文件。本实例包含以下集中属性:

  • foo.enabled, false by default
  • foo.remote-address, with a type that can be coerced from String
  • foo.security.username, with a nested "security" whose name is determined by the name of the property. In particular the return type is not used at all there and could have been SecurityProperties
  • foo.security.password
  • foo.security.roles, with a collection of String

 

package com.example;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
 

@ConfigurationProperties("foo")

public class FooProperties {


    private boolean enabled;

    private InetAddress remoteAddress;

    private final Security security = new Security();

    public boolean isEnabled() { ... }

    public void setEnabled(boolean enabled) { ... }

    public InetAddress getRemoteAddress() { ... }

    public void setRemoteAddress(InetAddress remoteAddress) { ... }

    public Security getSecurity() { ... }

    public static class Security {

        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

        public String getUsername() { ... }

        public void setUsername(String username) { ... }

        public String getPassword() { ... }

        public void setPassword(String password) { ... }

        public List<String> getRoles() { ... }

        public void setRoles(List<String> roles) { ... }

    }
}
 

 

  1. ConfigurationProperties和Component配置,定义一个bean

 

@Component

@ConfigurationProperties(prefix="foo")

public class FooProperties {


    // ... see above

}

 

     通过以上两种方式定义的bean,可以和普通bean一样使用。

 

     配置bean的属性,和配置文件中属性名称,有一种松散的绑定方式。

 

@ConfigurationProperties(prefix="person")public class OwnerProperties {

    private String firstName;

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

 

     其中firstName可以有以下集中定义方式:

 

person.firstName

 

Standard camel case syntax.

 

person.first-name

 

Dashed notation, recommended for use in .properties and .yml files.

 

person.first_name

 

Underscore notation, alternative format for use in .properties and .yml files.

 

PERSON_FIRST_NAME

 

Upper case format. Recommended when using a system environment variables.

 

 

@ConfigurationProperties的属性可以使用spring的 @Validated进行值的合法验证,也可以使用 JSR-303 javax.validation进行合法性验证。

 

@ConfigurationProperties vs. @Value

Feature@ConfigurationProperties@Value

Relaxed binding

Yes

No

Meta-data support

Yes

No

SpEL evaluation

No

Yes

转载于:https://my.oschina.net/u/347227/blog/868731

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值