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();





awesome thank you Jayesh. I tried @Component, but never worked. This time it works with Autowired
– Sree
Aug 30 at 17:10



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)