SpringBoot application.properties 详解

39 篇文章 1 订阅
14 篇文章 1 订阅

一、配置属性的定义

1.1 我们可以在 application.properties 中添加类似如下这样简单的常量配置:

my.name=张富
my.age=20

1.2 配置属性之间也可以相互引用使用:

my.name=张富
my.age=20
my.info=name:${my.name} age:${my.age}

1.3 配置文件中可以使用 ${random} 来生成各种不同类型的随机值:

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]}

1.4 将数据注入到属性上

1.5 在需要的地方我们使用 @Value 注解就可以将数据注入到属性上:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
 
@RestController
public class HelloController {
    @Value("${my.name}")
    String name;
 
    @GetMapping("/hello")
    public String hello() {
        return "welcome to " + name;
    }
}

二、将数据注入到 Bean 中

有时候属性太多了,一个个绑定到属性字段上太麻烦,官方提倡绑定一个对象的 bean。

2.1 首先我们创建一个名为 My 的 Bean,并将前面的配置数据注入到这个 Bean 中。

(1)@ConfigurationProperties 中的 prefix 属性描述了要加载的配置文件的前缀。
(2)Spring Boot 采用了一种宽松的规则来进行属性绑定:

假设 Bean 中的属性名为 authorName,那么配置文件中的属性可以是 my.author_name、my.author-name、my.authorName 或者 my.AUTHORNAME
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = “my”)
public class My {
private String name;
private String age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}

}

2.2 然后我们在 Controller 中引入这个 Bean 使用即可:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

@RestController
public class HelloController {
@Autowired
My my;

@GetMapping("/hello")
public String hello() {
    return my.getName() + " : " + my.getAge();
}

}

三、配置文件中的map和list类型配置参数

3.1 在properties中定义map格式的参数

#map 第一种方式
data.person.name=zhangfu
data.person.sex=man
data.person.age=11
data.person.url=xxxxxxxx

#map 第二种方式
data.person[name]=zhanggui
data.person[sex]=man
data.person[age]=22
data.person[url]=xxxxxxxx

3.2 代码中定义相匹配的map进行取值

@Data
@Configuration
@ConfigurationProperties(prefix = "data")
public class PersonConfig {

    /**
     * data.person.name
     * 这里map名需要和application.properties中的参数一致
     */
    private Map<String, String> person = new HashMap<>();
   
}

3.3 测试返回

{
    "top.sex": "man",
    "top.name": "zhangsan",
    "top.age": "11",
    "top.url": "xxxxxxxx"
}

3.4 在properties中定义map嵌套格式的参数

#map 第一种方式
#data.person.top.name=zhangsan
#data.person.top.sex=man
#data.person.top.age=11
#data.person.top.url=xxxxxxxx

#data.person.zoe.name=zhangsan
#data.person.zoe.sex=man
#data.person.zoe.age=11
#data.person.zoe.url=xxxxxxxx

#map 第二种方式
data.person.top[name]=zhangsan
data.person.top[sex]=man
data.person.top[age]=11
data.person.top[url]=xxxxxxxx

data.person.zoe[name]=zhangsan
data.person.zoe[sex]=man
data.person.zoe[age]=22
data.person.zoe[url]=xxxxxxxx

3.5 代码中定义相匹配的map (嵌套)进行取值

@Configuration
@ConfigurationProperties(prefix = "data")
public class PersonConfig {

    /**
     * data.person.name
     * 这里map名需要和application.properties中的参数一致
     */
    private Map<String, Map<String, String>> person = new HashMap<>();
}

3.6 map嵌套返回

{
    "top": {
        "name": "zhangsan",
        "sex": "man",
        "age": "11",
        "url": "xxxxxxxx"
    },
    "zop": {
        "name": "zhangsan",
        "sex": "man",
        "age": "22",
        "url": "xxxxxxxx"
    }
}

3.7 在properties中定义list格式的参数

##list 第一种方式
data.list[0]=apple0
data.list[1]=apple1
data.list[2]=apple2

##list 第二种方式
#data.list=apple0,apple1,apple2

3.8 代码中定义相匹配的list进行取值

@Configuration
@ConfigurationProperties(prefix = "data")
@Data
public class PersonConfig {

    private List<String> list = new ArrayList<>();
}

3.9 测试返回

[
    "apple0",
    "apple1",
    "apple2"
]

四、使用自定义的配置文件

(1)有时候我们不希望把所有配置都放在 application.properties 里面,这时候我们可以另外定义一个。假设我们自定义的配置文件是 test.properties,放在 src/main/resources 下面。

(2)新建一个 bean 类后,通过如下方式将这个自定义的配置文件数据注入进来:

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

@Component
@ConfigurationProperties(prefix = “my”)
@PropertySource(“classpath:test.properties”)
public class My {
private String name;
private String age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}

}

五、使用命令行参数进行配置

(1)在命令行中通过 java -jar 命令启动项目时,可以使用连续的两个减号 – 对 application.properties 中的属性值进行赋值。

(2)比如下面命令修改 tomcat 端口号为 8081。其等价于在 application.properties 中添加属性 server.port=8081:

注意:如果 application.properties 中已经有同名属性,那么命令行属性会覆盖 application.properties 的属性。

java -jar xx.jar --server.port=8081
配置文件的优先级

(1)Spring Boot 项目中的 application.properties 配置文件一共可以出现在如下 4 个位置(优先级逐渐降低):

项目根目录下的 config 文件夹
项目根目录下
classpath 下的 config 文件夹
classpath 下
(2)如果这 4 个地方都有 application.properties 文件,加载的优先级就是从 1 到 4 依次降低,Spring Boot 将按照这个优先级查找配置信息。

原文:SpringBoot - 配置文件application.properties使用详解(附:Profile多环境配置)

六、加载外部的配置文件

(1)项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定外部配置文件的位置。

java -jar xxx.jar --spring.config.location=/Volumes/BOOTCAMP/application.properties
(2)当然我们也可以指定外部配置所在的文件夹,启动时会搜索并使用该文件夹下的配置文件:

java -jar xxx.jar --spring.config.location=/Volumes/BOOTCAMP/
(3)我们还可以同时配置多个路径,比如下面样例先加载外部配置文件,如果不存在外部配置文件的话则使用包内默认的配置文件:

java -jar xxx.jar --spring.config.location=/Volumes/BOOTCAMP/application.properties,classpath:/,classpath:/config/
使用 Profile 实现多环境配置

我们在项目发布之前,一般需要频繁地在开发环境、测试环境以及生产环境之间进行切换,这个时候大量的配置需要频繁更改(比如数据库配置、redis 配置、mongodb 配置等等)。
Spring Boot 的 Profile 就给我们提供了解决方案,它约定不同环境下的配置文件名称规则为:

application-{profile}.properties,其中 {profile} 表示当前环境的名称。
(1)首先在 resources 目录下创建两个配置文件:application-dev.properties 和 application-prod.properties,分别表示开发环境中的配置和生产环境中的配置。

(2)它们两个分别设置不同的端口号。

#application-dev.properties
server.port=8080

#application-prod.properties
server.port=80
(1)假设我们在 application.properties 中进行如下配置,则表示使用 application-dev.properties 配置文件启动项目。

spring.profiles.active=dev
(2)如果将 dev 改为 prod,则表示使用 application-prod.properties 启动项目。

spring.profiles.active=prod
(3)项目启动成功后,就可以通过相应的端口进行访问了。

(1)除了像前面那样在 application.properties 中添加配置,我们也可以在代码中添加配置来完成。

(2)比如我们在启动类的 main 方法上添加如下代码,表示使用 application-dev.properties 配置文件启动项目。

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    SpringApplicationBuilder builder = new
            SpringApplicationBuilder(DemoApplication.class);
    builder.application().setAdditionalProfiles("dev");
    builder.run(args);
}

}
我们也可以在项目打包成 jar 包后启动时,在命令行中动态指定当前环境:

java -jar xxx.jar --spring.profiles.active=dev

七、自定义application.properties名字

默认情况下SpringBoot会自动读取/resources目录下的配置文件application-{profile}.properties,实际开发中,有时候想自定义配置文件名称,例如:将application.properties改为my.properties

```php
#环境:dev、test、prod
spring.profiles.active=dev

#端口配置
server.servlet.context-path=/pageHelper
server.error.path=/error
server.port=8097

SpringBoot就无法自动加载该配置文件了,可以通过以下两个方法解决:


**方法一:在启动类通过spring.config.location指定配文文件具体路径进行加载**
```java
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;

import java.util.*;

@Slf4j
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(DemoApplication.class).properties("spring.config.location=classpath:/my.properties").build().run();
    }
}

方法二:在启动类通过spring.config.name指定配置文件名字进行加载

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;

import java.util.*;

@Slf4j
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(DemoApplication.class).properties("spring.config.name:my.properties").build().run();
    }
}
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值