Reputation: 538
I am trying to pull data from application.properties file in Spring Boot
application.properties
host=localhost:8080
accountNumber=1234567890
TestController.java
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private TestService testServiceImpl;
@Value("${host}")
private String host;
@RequestMapping("/test")
public String test() {
testServiceImpl = new TestService();
return testServiceImpl.getValue();
}
TestServiceImpl.java
@Service
public class TestServiceImpl implements TestService{
@Value("${accountNumber}")
public String value;
public String getValue(){
return value;
}
When I do a REST call to localhost:8080/test, I get a null value.
TestServiceImpl
is instantiated however, @Value
does not seem to work.
Am I missing anything?
SOLUTION:
All I had to do was to remove the line testServiceImpl = new TestService();
I am assuming it was doing that because new TestService()
was overwriting the autowired instance of TestService
Upvotes: 1
Views: 2475
Reputation: 538
The solution I found was very simple.
All I had to do was to remove the line testServiceImpl = new TestService();
I am assumed it was doing that because new TestService() was overwriting the autowired instance of TestService.
Thank you harshavmb for verifying my solution.
Hope this helps many new Spring-ers :)
Upvotes: 0
Reputation: 974
To update :
Spring's DI achieved via @Autowired annotation.It creates the object for us.
@Autowired
private TestService testServiceImpl;
.
.
.
@RequestMapping("/test")
public String test() {
// testServiceImpl = new TestService(); // make comment this line
return testServiceImpl.getValue();
}
Upvotes: 3