1. 程式人生 > 實用技巧 >SpringBoot之讀取配置檔案中自定義的值

SpringBoot之讀取配置檔案中自定義的值

SpringBoot之讀取配置檔案中自定義的值

概念:

  一般來說,我們會在配置檔案中自定義一些自己需要的值,比如jwt的密匙,或者一些FTP配置等資訊

如何獲取:

  定義自己需要的屬性

  

獲取方式一:

  使用Spring上下文中的環境獲取

  

  

獲取方式二:

  使用@Value註解獲取

  

  

獲取方式三:

  通過@ConfigurationProperties註解獲取,指定字首,自動對映成物件,@PropertySource可以指定配置檔案,使用@ConfigurationProperties註解的前提必須使用@Component註解註釋成一個Bean

package com.springboot.demo.model;

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

/**
 * Component 定義為元件
 * ConfigurationProperties 通過字首+屬性自動注入
 * PropertySource 指定配置檔案
 
*/ @Component @ConfigurationProperties(prefix = "flower",ignoreUnknownFields = true) @PropertySource(value = { "classpath:application.yml" }) public class Flower { private String name; private String age; public Flower(String name, String age) { this.name = name; this.age = age; }
public Flower() { } 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; } @Override public String toString() { return "Flower{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } }

  

  

測試:

  重啟專案後統一測試

  介面一測試結果:

    

  介面二測試結果:

    

  介面三測試結果:

    

經過測試可以得知三種方法都可以獲取配置檔案中的值,其中都是可以組合使用的,比如@ConfigurationProperties+@Value等互相組合

作者:彼岸舞

時間:2021\01\12

內容關於:SpringBoot

本文來源於網路,只做技術分享,一概不負任何責任

package com.springboot.demo.model;

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

/**
* Component 定義為元件
* ConfigurationProperties 通過字首+屬性自動注入
* PropertySource 指定配置檔案
*/
@Component
@ConfigurationProperties(prefix = "flower",ignoreUnknownFields = true)
@PropertySource(value = { "classpath:application.yml" })
public class Flower {

private String name;

private String age;

public Flower(String name, String age) {
this.name = name;
this.age = age;
}

public Flower() {
}

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

@Override
public String toString() {
return "Flower{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}