深刻理解SpringBoot配置

1、application.properties的位置

1.当前目录的 “/config”的子目录下
2.当前目录下
3.classpath根目录的“/config”包下
4.classpath的根目录下html

spring会从classpath下的/config目录或者classpath的根目录查找application.properties或application.yml。java

/config优先于classpath根目录spring

说明:mongodb

  1. 1,2两项适合生产环境,能够直接跟jar包放在同级目录下
  2. 若是同时在四个地方都有配置文件,配置文件的优先级是从1到4。
  3. 使用配置文件以后,spring boo启动时,会自动把配置信息读取到spring容器中,并覆盖spring boot的默认配置

SpringBoot的配置方式有不少,它们的优先级以下所示(优先级递减顺序):express

  1. 命令行参数
  2. 来自java:comp/env的JNDI属性
  3. Java系统属性(System.getProperties())
  4. 操做系统环境变量
  5. RandomValuePropertySource配置的random.*属性值
  6. jar包外部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  7. jar包内部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  8. jar包外部的application.propertiesapplication.yml(不带spring.profile)配置文件
  9. jar包内部的application.propertiesapplication.yml(不带spring.profile)配置文件
  10. @Configuration注解类上的@PropertySource
  11. 经过SpringApplication.setDefaultProperties指定的默认属性

由于jar包外部的优先级高,因此能够运行时指定application.properties的位置。
以上配置方式虽然挺多,实际用到的只有一两种。json

2、 经过命令行来配置少许项

SpringBoot能够不依赖Tomcat容器,做为单应用启动。这时,能够经过命令行来控制运行参数。
经过命令行来重写和配置环境变量,优先级最高,例如能够经过下面的命令来重写spring boot 内嵌tomcat的服务端口,注意“=”俩边不要有空格
java -jar demo.jar --server.port=9000
若是想要设置多个变量怎么办,能够用json的格式字符串来设置
java -jar demo.jar --spring.application.json='{"foo":"bar"}'tomcat

3、 使用@Value注解

@RestController
@RequestMapping("/task")
public class TaskController {

@Value("${connection.remoteAddress}") private String address;

@RequestMapping(value = {"/",""})
public String hellTask(@Value("${connection.username}")String name){

    return "hello task !!";
}
}

@Value注解有好几种姿式:
1. #{expression?:default value}springboot

@Value("#{systemProjecties['mongodb.port']?:27017}")
private String mongodbPort;
@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
@Value("#{aBean.age ?:21}")
private int age;

2. ${property:default value}session

//@propertySource("classpath:/config.properties")
//configuration
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongoUrl;
@Value("#config['mongodb.url']?:'127.0.0.1'")
private String mogodbUrl;

配置文件config.property以下:app

mogodb.url = 1.2.3.4
mogodb.db = hello

3. 注意
Must register a static PropertySourcesPlaceholderConfiger bean in either XML or annotation ,so that Spring @Value konw how to interpret ${}

//@PropertySource("classpath:/config.properties}")
//@Configuration
  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
         return new PropertySourcesPlaceholderConfigurer();
  }

4、 属性的引用

myapp.name=spring
myapp.desc=${myapp.name} nice
SpringBoot提供如下特殊引用:
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]}

5、 自定义配置信息

@Component
public class SystemConfig {

    private static Properties props ;

    public SystemConfig(){

        try {
            Resource resource = new ClassPathResource("/application.properties");//
            props = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取属性
     * @param key
     * @return
     */
    public static String getProperty(String key){

        return props == null ? null :  props.getProperty(key);

    }

    /**
     * 获取属性
     * @param key 属性key
     * @param defaultValue 属性value
     * @return
     */
    public static String getProperty(String key,String defaultValue){

         return props == null ? null : props.getProperty(key, defaultValue);

    }

    /**
     * 获取properyies属性
     * @return
     */
    public static Properties getProperties(){
        return props;
    }

}

//用的话,就直接这样子
String value = SystemConfig.getProperty("key");

6、SpringBoot自带的配置属性

经常使用属性如日志,端口配置

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'

更多属性参见官网文档

@ContextConfiguration
@ContextConfiguration(locations={"classpath*:mongodb.xml"})

7、属性名匹配规则

例若有以下配置对象:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {

    private String firstName;

}

firstName可使用的属性名以下:

person.firstName,标准的驼峰式命名
person.first-name,虚线(-)分割方式,推荐在.properties和.yml配置文件中使用
PERSON_FIRST_NAME,大写下划线形式,建议在系统环境变量中使用

参考资料

偶尔记一下

相关文章
相关标签/搜索