我正在使用Spring Boot编写一个REST服务。
rest服务中的方法调用util类,该util类需要引用application.properties中定义的某些属性
我使用user @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可读?
发布于 2018-08-30 08:47:08
使您的Util类成为spring的一个组件。@Value仅适用于spring托管依赖项
@Component
public class MyUtil{
@Value("${report.path}")
private String reportPath;
public String test(){
return reportPath;
}
}
确保将MyUtil的包添加到组件扫描中
..and将MyUtil作为自动连接依赖项使用,如下所示
@RestController
@RequestMapping("/api/v1")
public class ReportsController{
@Autowired
private MyUtil myUtil;
public void someMethod() {
myUtil.reportPath();
}
https://stackoverflow.com/questions/52087746
复制相似问题