【问题标题】:How to read application.properties in utils class如何在 utils 类中读取 application.properties
【发布时间】:2018-08-30 00:32:00
【问题描述】:

我正在使用 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 可读?

【问题讨论】:

    标签: spring rest spring-boot


    【解决方案1】:

    让你的 Util 类成为 spring 的一个组件。 @Value 仅适用于 spring 管理的依赖项

    @Component
    public class  MyUtil{
    
     @Value("${report.path}")
     private String reportPath;
    
     public String test(){
         return reportPath;
     } 
    }
    

    确保将 MyUtil 的包添加到组件扫描中

    ..并使用 MyUtil 作为 Autowired 依赖项,无论您想使用什么

    @RestController
    @RequestMapping("/api/v1")
    public class ReportsController{
    
    @Autowired
    private MyUtil myUtil;
    
    public void someMethod() {
       myUtil.reportPath();
    }
    

    【讨论】:

    • 太棒了,谢谢杰伊什。我尝试了@Component,但从未奏效。这次它适用于 Autowired
    • Jayesh,但是测试呢?我们如何测试 util 类?
    • 这就像编写任何弹簧测试一样简单。使用@Runwith(SpringJunitTestTunner) 或使用@springboottest。你可以找到很多例子
    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2016-06-03
    • 2020-09-12
    • 1970-01-01
    • 2020-10-10
    • 2020-06-29
    • 2018-01-07
    • 2015-05-23
    相关资源
    最近更新 更多