1

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

4
  • 1
    Great that you solved your own problem. You are welcome to post your answer as an answer. SO encourages people to answer your own question. stackoverflow.com/help/self-answer Commented Jun 1, 2017 at 4:05
  • 1
    Since you autowired testServiceImpl, spring container will create the bean for you and you said NO by creating instance yourself with new TestService() meddling with spring. Commented Jun 1, 2017 at 4:07
  • @harshavmb Yes you are right. That is what I found to be the problem. Thank you for validating my finding! Commented Jun 2, 2017 at 23:51
  • Glad to hear that you resolved! Commented Jun 3, 2017 at 2:19

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.