@Value获取值和@ConfigurationProperties获取值比较

另外对于复杂类型封装,@ConfigurationProperties支持, @Value不支持。
无论配置文件yml还是properties他们都能获取到值。
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
还是在之前的代码基础上新建HelloController类,并将Person类中的@ConfigurationProperties给注释掉;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${person.last-name}")
private String name;
@RequestMapping("/sayHello")
public String sayHello(){
return "Hello"+name;
}
}
运行,在浏览器上输入http://localhost:8081/sayHello

如果说我们专门编写了javaBean来和配置文件进行映射时,我们就直接使用@ConfigurationProperties;
谈谈SpringBoot配置文件(六)
本文主要对比了Spring Boot中@Value和@ConfigurationProperties获取配置文件值的差异。二者在yml和properties文件中都能获取值,但@ConfigurationProperties支持复杂类型封装,@Value不支持。业务逻辑中取单项值用@Value,编写javaBean与配置文件映射用@ConfigurationProperties。
9414

被折叠的 条评论
为什么被折叠?



