spring - 如何在 utils 类中读取 application.properties
问题描述
我正在使用 Spring Boot 编写 REST 服务。
我的 rest 服务中的方法调用了一个 util 类,这个 util 类需要引用 application.properties 中定义的某些属性
我使用@Value,但它在 util 类中不起作用,而它在我的 REST 服务类中起作用。
我的 REST 服务:ReportsController.java
@RestController
@RequestMapping("/api/v1")
public class ReportsController{
@Value("${report.path}")
private String reportPath;
@GetMapping
@RequestMapping("/welcome")
public String retrieveWelcomeMessage() {
return new ExcelFileUtil().test();
}
@GetMapping
@RequestMapping("/welcome1")
public String retrieveWelcomeMessage() {
return reportPath;
}
}
我的 Utils 类:MyUtil.java
public class MyUtil{
@Value("${report.path}")
private String reportPath;
public String test()
{
return reportPath;
}
}
我从 application.properties 获取值打印为http://localhost:8080/api/v1/welcome1但为http://localhost:8080/api/v1/welcome打印为 空白
如何使 myUtil.java 中的 application.properties 可读?
解决方案
让你的 Util 类成为 spring 的一个组件。@Value 仅适用于 spring 管理的依赖项
@Component
public class MyUtil{
@Value("${report.path}")
private String reportPath;
public String test(){
return reportPath;
}
}
确保将 MyUtil 的包添加到 component-scan
..并使用 MyUtil 作为 Autowired 依赖项,无论您想使用什么
@RestController
@RequestMapping("/api/v1")
public class ReportsController{
@Autowired
private MyUtil myUtil;
public void someMethod() {
myUtil.reportPath();
}
推荐阅读
- git - git submodule:如何区分特定的超级项目提交?
- websocket - MQTT Websocket Arduino Uno 与 SIM7600
- javascript - Chartjs 时间戳到日期时间标签
- python - 使用python实现二叉树
- python - Python 使用 BeautifulSoup 和 PIL 从 url 获取图像路径和大小
- android - Android Studio 项目不会为 Main Activity 生成绑定对象
- cmake - CMake:目标不在导出集中
- mysql - InnoDB 缓冲池大小占总 RAM 的百分比 - (总 RAM 的缓冲池大小)返回无数据
- python - 在 Python 中实现矩形矩阵的伪谱
- html - 内联“详细信息”元素:搜索问题