@ConfigurationProperties和@Value的一个共同点就是从配置文件中读取配置项。
发现有一点区别,我项目配置中并没有配置hello.msg
,当使用第一段代码时,启动后读取到msg为null,而第二段代码则会抛出异常。第二段代码有个好处,就是防止我们配置项遗漏,当遗漏时,启动程序肯定出错,这样避免了一些因为遗漏配置项导致的BUG.
第一段代码
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("hello")
public class HelloProperties {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
第二段代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Hello2Properties {
@Value("${hello.msg}")
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}