springboot 的@value取不到正確的值
- 寫了一個簡單的屬性注入demo,發現個問題,因爲開發中習慣性的寫user,所以恰好問題也出在這裏。
- 代碼如下
package com.demo.zz;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class zz {
public static void main(String[] args) {
SpringApplication.run(zz.class, args);
System.err.println(44566);
}
@Value("${user.name}")
private String name;
@RequestMapping("/getinfo")
public String getInfo() {
return "name is :" + name+age;
}
}
- application.properties中的配置
server.port=8852
user.name=sdfas
user.age=155
測試結果
- 我們在postman或者瀏覽器中訪問這個接口,最開始當我們的配置文件中值有name時,我們獲取到的值是自己電腦的主機名
- 當我們的只注入user.age時,會發現不能解析這個註解。會發生參數異常
備註
項目中最好不用user來當做配置文件中屬性