首頁  >  文章  >  Java  >  Spring Boot讀取配置4種方式,建議收藏!

Spring Boot讀取配置4種方式,建議收藏!

Java后端技术全栈
Java后端技术全栈轉載
2023-08-15 16:06:231222瀏覽

在Spring Boot專案中基本上都會涉及到讀取設定檔內容,本文就來聊聊常見的讀取設定檔的幾種方式。

Value註解

#在application.properties設定檔設定項:

name=tian

在java程式碼中讀取:

/**
 * @author tianwc  公众号:java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年07月02日 21:00
 * 博客地址:<a href="http://woaijava.cc/">博客地址</a>
 */
@RestController
@RequestMapping("/configuration")
public class ConfigurationController {

    @Value("${name}")
    private String name;

    @GetMapping("/index")
    public String test() {
        return name;
    }
}

驗證:

GET

#http://localhost:8089/configuration/index

傳回參數:

tian

這類通常都是沒有前綴,比較單一的設定項會採用這麼讀取。

如果有相同的前綴配置,那麼我們可以使用下面這種方法。

ConfigurationProperties註解

#在application.properties設定檔設定項:

user.userName=tian1
user.age=21

在javadiam中讀取:

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

/**
 * @author tianwc  公众号:java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年07月02日 21:07
 * 博客地址:<a href="http://woaijava.cc/">博客地址</a>
 */
@Component
@ConfigurationProperties(prefix = "user")
public class PreConfiguration {
    private String userName;
    private Integer age;

    //set get 省略
}

驗證:

GET

#http://localhost:8089/preconfiguration/index

我們通常是把一類的配置項設定為前綴,並統一處理,物件導向化。

但,如果是讀取多個的如何處理(陣列類型)?

我們可以採用下面這種方式。

也是ConfigurationProperties注解

application.properties配置文件配置项:

vip.userList[0].name=tian01
vip.userList[0].age=20
vip.userList[1].name=tian02
vip.userList[1].age=21

定义一个User类:

public class User {
    private String name;
    private Integer age;
    
    //set get toString 省略
}

配置读取类:

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

import java.util.List;

/**
 * @author tianwc  公众号:java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年07月02日 21:24
 * 博客地址:<a href="http://woaijava.cc/">博客地址</a>
 */
@Component
@ConfigurationProperties(prefix = "vip")
public class UserListConfiguration {
    private List<User> userList;
    // set get 省略
}

如果我们自定义一个custom.properties配置文件,那又该如何读取呢?

PropertySource注解

application.properties配置文件配置项:

realName=tian3

代码实现

@RestController
@RequestMapping("/propertySource")
@PropertySource("classpath:custom.properties")
public class PropertySourceController {

    @Value("${realName}")
    private String realName;
    @GetMapping("/index")
    public String test() {
        return realName;
    }
}

验证:

GET

http://localhost:8089/propertySource/index

返回参数:tian3

那么,问题又来了,我们可能会因为一个配置项需要改,或者是上线后发现配置项不对,这时候就需要重启服务了,为了避免这样重启服务,我们可以引入分布式配置中心

分布式配置中心有很多实现方案,比如Nacos、Zookeeper、Qconf、disconf、Apache Commons Configuration、Spring Cloud Config等。

以上是Spring Boot讀取配置4種方式,建議收藏!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:Java后端技术全栈。如有侵權,請聯絡admin@php.cn刪除