首页 > 解决方案 > 如何在 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 可读?

标签: springrestspring-boot

解决方案


让你的 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();
}

推荐阅读