卜若的代碼筆記系列-Web系列-SpringBoot-第十章:@Value("${}")-3210


卜若的代碼筆記系列-Web系列-SpringBoot-第十章:@Value("${}")-3210

問題背景:我們通常會在寫服務的時候遇到這樣一個需求。
我們配置密碼,賬號。
爲什麼會遇到這個需求呢,舉個例子,我們想要配置一個登陸的權限
也就是說,你需要輸入賬號和密碼才能登陸這個網站。
我們有很多種辦法。
比如:我們可以將這個賬號和密碼放在數據庫裏,通過連接數據庫
然後進行匹配。
但是,在有的時候,我們其實並不想去連接數據庫,我們只想使用一個
txt之類的文件去記錄就行。
於是,在這個問題提出之後我們產生了使用@Value("${xx.xxx.xxx}")
來將數據和源代碼分離的作用。

算起來,這也算是面向接口的一部分了。


1.springboot裏面提供了一個.properties的文件


我們可以在這裏面定義一些字段。

比如我的這個項目
圖片:

application.properties

我在裏面定義一個字段

test.testList.a1 = 9443;

2.通過@Value(${test.testList.a1});
將該值賦給我們定義的一個字段

如:我們在FileController裏面定義了一個
String的字段:

private String a1;

現在我們賦值

@Value("${test.testList.a1}")
private String a1;

我們測試下,使用System.out.println(a1);
將數據打印出來;

@RestController
@RequestMapping("/file")
public class FileController {
    
    @Value("${test.testList.a1}")
    private String a1;
    
    
    @RequestMapping("/testValue")
    public void testValue()
    {
        
        
        System.out.print(a1);
    }
}


結果:
圖片:


3.現在,我們還有一個問題,假如我們不在application.properties裏面定義字段
我們想新建一個password.properties的文件來管理這些字段呢,是不是也可以直接
這樣就行了?
我們試試:

    我們嘗試添加test.properties文件:

並且將數據test.testList.a1 = 9443放到這個.properties文件

報錯

org.springframework.beans.factory.BeanCreationException: Error creating bean with 
name 'fileController': Injection of autowired dependencies failed; nested exception 
is java.lang.IllegalArgumentException: Could not resolve placeholder 'test.testList.a1' 
in value "${test.testList.a1}"

它的意思總結起來就是無法給將test.testList.a1的值送給${test.testList.a1}

顯然,它的原因肯定是因爲我們沒有註冊這個test.properties,所以@Value("${}")這個批註就拿不到這個test.properties的內容

所以,我們需要通過正規手段去註冊這個.properties。

 

4.註冊:

 

怎麼註冊,當然,通常情況下我們會去想是在web.xml裏面去註冊,這也是在我在學習mvc後的第一反應,但是在springboot裏面

是沒有web.xml(它隱藏了,當然,你也可以手動創建,之後肯定是一系列複雜的配置,所以,我們通常會拒絕這種辦法)

 

所以,查閱了一些資料:

這樣,我們可以將這個類通過

@PropertySource( "classpath:test.properties")


配置它的@Value源,這樣我們就能夠使用這個.properties的字段了

@PropertySource( "classpath:test.properties")
@RestController
@RequestMapping("/file")
public class FileController {
    
    @Value("${test.testList.a1}")
    private String a1;    
    @RequestMapping("/testValue")
    public void testValue()
    {
        System.out.print(a1);
    }

}

結果:

 5.現在,我們有個新的問題,如果使用這個

@PropertySource( "classpath:test.properties")

批註,那我們還能不能獲取到application.properties裏面的資源呢?

我們做個試驗:

 

答案是可以的!!!!!!!!!!!!!!!!

 

6.我們產生了新的疑問,假如,我要定義一個新的test2.properties可不可以同時使用呢?

我們做個試驗:

答案顯而易見,可以咯~

ps:我的郵箱[email protected],歡迎有問題的同學發郵件共同交流~ 

 

 

 

 

引用:

http://www.javashuo.com/article/p-yziikwyx-de.html

https://blog.csdn.net/fjnpysh/article/details/74360111