如何在utils类中读取application.properties

时间:2018-08-30 00:32:01

标签: spring rest spring-boot

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

一片空白

如何使application.properties在MyUtil.java中可读?

1 个答案:

答案 0 :(得分:3)

使Util类成为spring的组成部分。 @Value仅适用于Spring托管的依赖项

@Component
public class  MyUtil{

 @Value("${report.path}")
 private String reportPath;

 public String test(){
     return reportPath;
 } 
}

确保将MyUtil软件包添加到component-scan

..然后将MyUtil用作想要自动使用的依赖项

@RestController
@RequestMapping("/api/v1")
public class ReportsController{

@Autowired
private MyUtil myUtil;

public void someMethod() {
   myUtil.reportPath();
}