spring boot/cloud 注入yml / properties文件配置信息@Value註解注入static靜態方法失敗問題,及中文亂碼問題

 

場景

@Value 註解在 static 靜態方法中注入失敗,得到結果null ,

原因:@value不能直接注入值給靜態屬性,spring 不允許/不支持把值注入到靜態變量中。

錯誤案例:取值不到,null

@Value("${test01}")
private static String test01;

----------------------------------------------------------------------------------------------------------------------------------------

 註解:

@Value("${test01}")

使用方法

  • yml文件配置信息
test01: halloWorld
  • 非靜態
@Value("${test01}")
private String test01;

public void test() {
    System.out.println("test01:"+test01);
}
  • 靜態

private String test01;

@Value("${test01}")
public void setTest01(String test01) {
   this.test01 = test01;
}

public static void test() {
    System.out.println("test01:"+test01);
}

還可使用另一種方案

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class YmlConfig {
    //靜態方法取值
    public static String TEST01;
    public static String TEST02;

    //其他方法取值
    @Value("${test01}")
    private String test01;
    @Value("${test02}")
    private String test02;

    @PostConstruct
    public void init() {
        TEST01 = this.test01;
        TEST02 = this.test02;        
    }
}

 使用

@Autowired
private YmlConfig config;


public void Test01(String test01) {
   String test01 = config.TEST01;
   System.out.println(test01);

   //有寫get方法也可以這樣使用
   String test02 = config.getTest02();
   System.out.println(test02);
}

/**
 * 靜態方法
 */
public static void Test01(String test01) {
   String test01 = config.TEST01;
   System.out.println(test01);
}

 

.properites 中文亂碼問題解決

test02: 中文

使用@Value 的方式獲取得到亂碼,原因:用@Value註解讀取application.properties文件時,編碼默認是ISO-8859-1

解決的方式很多,但是大廠都會把中文轉換成 unicode 方式,因爲代碼中除了註釋,其他都避免出現中文。

解決方案

test02: \u4e2d\u6587

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章