ron
ron

Reputation: 229

Spring boot access application.properties in components

I want to add a property in application.properties of my spring boot application and be able to to access it and use it in one of my other classes, but I am getting null.

Here is my application.properties

server.port=8052
subscribe.period=5

My class that will access it

@Component
public class SubscriptionService {

    @Value("${subscribe.period}")
    private String period

    @Autowired
    public SubscriptionService(String period) {
        String time = period;
        ...
    }

}

But it seems period is not being populated, in fact null. It shows as nill when I run as maven build in eclipse at least, im thinking it might be trying to access it before the properties file is even load, if so how might i approach this?

Upvotes: 1

Views: 2530

Answers (1)

ron
ron

Reputation: 229

Deinum in the comments above is correct. I have no idea why as it differs from every other online example I have read so I would invite him to give an explanation.

I had to put the @Value in the argument of the constructor

@Component
public class SubscriptionService {

private String period

@Autowired
public SubscriptionService(@Value("${subscribe.period}") String period) {
    String time = period;
    ...
}

}

Then it works

Upvotes: 1

Related Questions