所以我对Springboot有点陌生,我正在尝试从application.properties中获得价值。我希望从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);
}
}是因为调用类时没有注入值,还是应该做什么?感谢任何帮助。谢谢!
发布于 2022-11-01 06:43:34
你好,朋友,当您将类声明为Spring时,您不应该自己初始化对象,因为Spring中定义的属性不会被spring注入,所以您应该让spring帮助您,尝试下面的类
NameProperties
@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;
}
}NameConfiguration.java
@Component
public class NameConfiguration {
@Autowired
NameProperties property;
public void getName(int index) {
System.out.println(property.getName().get(0));
}
}https://stackoverflow.com/questions/74271473
复制相似问题