溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot之@Value獲取application.properties配置無效怎么解決

發(fā)布時間:2023-05-18 11:50:53 來源:億速云 閱讀:109 作者:iii 欄目:編程語言

今天小編給大家分享一下SpringBoot之@Value獲取application.properties配置無效怎么解決的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

@Value獲取application.properties配置無效問題

無效的原因主要是要注意@Value使用的注意事項:

  • 1、不能作用于靜態(tài)變量(static);

  • 2、不能作用于常量(final);

  • 3、不能在非注冊的類中使用(需使用@Componet、@Configuration等);

  • 4、使用有這個屬性的類時,只能通過@Autowired的方式,用new的方式是不會自動注入這些配置的。

這些注意事項也是由它的原理決定的:

springboot啟動過程中,有兩個比較重要的過程,如下:

  • 1 、掃描,解析容器中的bean注冊到beanFactory上去,就像是信息登記一樣。

  • 2、 實例化、初始化這些掃描到的bean。

@Value的解析就是在第二個階段。BeanPostProcessor定義了bean初始化前后用戶可以對bean進行操作的接口方法,它的一個重要實現類AutowiredAnnotationBeanPostProcessor正如javadoc所說的那樣,為bean中的@Autowired和@Value注解的注入功能提供支持。

下面說下兩種方式:

resource.test.imageServer=http://image.everest.com

1、第一種

@Configuration
public class EverestConfig {
 
    @Value("${resource.test.imageServer}")
    private String imageServer;
 
    public String getImageServer() {
        return imageServer;
    }
 
}

2、第二種

@Component
@ConfigurationProperties(prefix = "resource.test")
public class TestUtil {
 
    public String imageServer;
 
    public String getImageServer() {
        return imageServer;
    }
 
    public void setImageServer(String imageServer) {
        this.imageServer = imageServer;
    }
}

然后在需要的地方注入就可

    @Autowired
    private TestUtil testUtil;
 
    @Autowired
    private EverestConfig everestConfig;
 
 
    @GetMapping("getImageServer")
    public String getImageServer() {
        return testUtil.getImageServer();
//        return everestConfig.getImageServer();
    }

@Value獲取application.properties中的配置取值為Null

@Value("${spring.datasource.url}")

private String url;

獲取值為NUll。

解決方法

不要使用new的方法去創(chuàng)建工具類(DBUtils)對象,而是使用@Autowired的方式交由springboot來管理,在工具類上加上@Component,定義的屬性變量不要加static。

正確做法
@Autowired
private DBUtils jdbc;
  
@Component
public class DBUtils{
    
    @Value("${spring.datasource.url}")
    private String url;
}

以上就是“SpringBoot之@Value獲取application.properties配置無效怎么解決”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI