How to read application.properties in utils class
How to read application.properties in utils class
I am writing a REST service using Spring Boot.
Method in my rest service calls a util class and this util class needs to refer certain properties defined in the application.properties
I user @Value and it didnt work inside the util class, where as it works in my REST service class.
My REST service: 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;
My Utils class: MyUtil.java
public class MyUtil
@Value("$report.path")
private String reportPath;
public String test()
return reportPath;
I am getting the value from application.properties is printed for http://localhost:8080/api/v1/welcome1
But getting blank for http://localhost:8080/api/v1/welcome
How to make the application.properties readable inside the MyUtil.java?
1 Answer
1
Make your Util class as a component of spring. @Value will work only on spring managed dependencies
@Component
public class MyUtil
@Value("$report.path")
private String reportPath;
public String test()
return reportPath;
Make sure the package of MyUtil is added to component-scan
..and use the MyUtil as a Autowired dependency whereever you want to use like
@RestController
@RequestMapping("/api/v1")
public class ReportsController{
@Autowired
private MyUtil myUtil;
public void someMethod()
myUtil.reportPath();
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
awesome thank you Jayesh. I tried @Component, but never worked. This time it works with Autowired
– Sree
Aug 30 at 17:10