所以我對 Springboot 有點陌生,我正在嘗試從 application.properties 中獲取價值。我想從 application.properties 中獲取多個值并將其插入到串列中。起初,我試圖從控制器類中獲取值并且它有效。現在我試圖從一個新類中獲取值,但是該值不會顯示并且它顯示錯誤,因為它說它是空的。我錯過了注釋還是在代碼中做錯了什么?下面是我的代碼。
應用程式屬性:
example.name[0] = asdf
example.name[1] = qwer
串列值類:
@ConfigurationProperties(prefix = "example")
@Configuration
public class NameProperties {
private List<String> name;
public List<String> getName() {
return name;
}
public void setName(List<String> name) {
this.name = name;
}
}
我在控制器中嘗試并作業的內容:
@RestController
@CrossOrigin
@RequestMapping("/tes/**")
public class NameController {
@Autowired
NameProperties property = new NameProperties();
@GetMapping
public String tes() {
String name = property.getName().get(0);
System.out.println(name);
return name;
}
}
在不起作用的新課程中:
@Component
public class NameConfiguration {
@Autowired
NameProperties property = new NameProperties();
public void getName(int index) {
System.out.println(property.getName().get(0));
}
}
在控制器中測驗新類的代碼:
@RestController
@CrossOrigin
@RequestMapping("/tes/**")
public class NameController {
NameConfiguration conf = new NameConfiguration();
@GetMapping
public String tes() {
conf.getName(0);
}
}
是因為當我呼叫類時沒有注入值還是我應該怎么做?感謝任何形式的幫助。謝謝!
uj5u.com熱心網友回復:
你好朋友,當你將你的類宣告為 Spring Bean 時,你不應該自己初始化物件,否則其中定義的屬性不會被 Spring 注入,所以你應該讓 spring 幫助你,試試下面的這些類
名稱屬性
@Component
@ConfigurationProperties(prefix = "example")
public class NameProperties {
private List<String> name;
public List<String> getName() {
return name;
}
public void setName(List<String> name) {
this.name = name;
}
}
名稱配置.java
@Component
public class NameConfiguration {
@Autowired
NameProperties property;
public void getName(int index) {
System.out.println(property.getName().get(0));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524817.html
標籤:弹簧靴弹簧注释
