I am trying to access application.properties
values in spring boot application's service class. But every time value is null, so it throws NullPointException
. I can get the right value for port in controller class(if i add @Autowired
in controller) but not in service class. What changes are required to make this properties available through out the application?
Controller looks like:
@RestController
public class MyController {
MyService ss = new MyService();
@RequestMapping(value = "/myapp/abcd", method = RequestMethod.POST, consumes = {"application/json"})
public ResponseMessage sendPostMethod(@RequestBody String request) {
log.debug(" POST Request received successfully; And request body is:"+ request);
ResponseMessage response = ss.processRequest(request);
return response;
}
}
And Service class is:
@Service
public class MyService {
private ApplicationProperties p;
@Autowired
public setProps(ApplicationProperties config) {
this.p = config;
}
public ResponseMessage processRequest(String request) {
System.out.println("Property value is:"+ p.getPort());
}
}
ApplicationProperties.java looks like:
@Component
@Getter
@Setter
@ConfigurationProperties
public class ApplicationProperties {
String port;
}
Finally, application.properties
file has:
port=1234
I have even tried passing ApplicationProperties
instance from controller to service's default constructor, but it did not work. When I debug, value persist while application startup, but when I make a rest web service POST call, it is null.
In your controller MyController
, you have to inject the service, replacing:
MyService ss = new MyService();
by:
@Autowired
MyService ss;
Also, instead of your ApplicationProperties
class, you can use @Value
annotation, from Spring, to load properties from application.properties
file. Take a look at this code:
import org.springframework.beans.factory.annotation.Value;
// ...
@Service
public class MyService {
@Value("${port}")
private String port;
// ...
}