I want to access some values from my application.properties
file, I tried using below method but not getting value.
application.property file
welcome.message=My message
Mycontroller.java
@RestController
class MessageRestController {
@Autowired MainConfigFiles mainConfigFiles;
@Value("${welcome.message}")
private String message;
@RequestMapping("/message")
String getMessage() {
return this.message;
}
@RequestMapping("/message2")
String getMessage2() {
MainConfigFiles a = new MainConfigFiles();
String msg = a.getMessage2();
System.out.println("Msg is....." msg);
return msg;
}
MainConfigFiles.java
@Configuration
@PropertySource(value = "application.properties")
public class MainConfigFiles {
@Value("${welcome.message}")
private String message2;
public String getMessage2() {
return message2;
}
}
I am able to get the value using
@RequestMapping("/message")
which is mentioned in the same file but unable to get the value when using @RequestMapping("/message2")
which mentioned in another class.
CodePudding user response:
First you need to read the welcome.message value from application.properties file and set it to MainConfigFiles. Later use this MainConfigFiles class(that you are already using @Autowire) and get that message.
Modify MainConfigFiles class as below.
public class MainConfigFiles {
Value("${welcome.message}")
private String message2;
Bean
public MainConfigFiles jpaConfig() {
MainConfigFiles mainConfigFiles = new MainConfigFiles();
mainConfigFiles.setMessage2(message2);
return mainConfigFiles;
}
public String getMessage2() {
return message2;
}
public void setMessage2(String message2) {
this.message2 = message2;
}
}
This is your MessageRestController.
@RestController
public class MessageRestController {
@Autowired
private MainConfigFiles mainConfigFiles;
@Value("${welcome.message}")
private String message;
@RequestMapping("/message")
String getMessage() {
return this.message;
}
@RequestMapping("/message2")
String getMessage2() {
String msg = mainConfigFiles.getMessage2();
System.out.println("Msg is....." msg);
return msg;
}
}