我的原因是 类被new新建了实例,而没有使用@Autowired,要使用@Autowired
首先使用@Value
第一步:有一个User实体
@Data
@Component
@ConfigurationProperties(prefix = "book")
public class User {
@Value("{book.name}")
private String name;
@Value("${book.author}")
private String author;
}
第二步:有一个Controller
@RestController
public class BookController {
@Autowired
User user;
@RequestMapping("/")
public String Index(){
String str = user.getName();
System.out.print(str);
return "你好,欢迎使用"+str;
}
}
第三步:配置文件写入内容
book.name=s
book.author=u
最后运行一下即可成功。
这之前要导入依赖,idea还要安装lombok插件