Defining application-specific, custom-defined properties

Up until now, we have looked at using prebuilt properties provided by Spring Boot for various frameworks. In this section, we will look at creating our application-specific configuration, which that can also be configured in application.properties.

Let's consider an example—we want to be able to interact with an external service. We want to be able to externalize the configuration of the URL of this service. The following example shows how we would want to configure the external service in application.properties:

somedataservice.url=http://abc.service.com/something

We want to use the value of the somedataservice.url property in our data service. The following snippet shows how we can do that in an example data service:

    @Component
public class SomeDataService {

@Value("${somedataservice.url}")
private String url;

public String retrieveSomeData() {
// TODO - Logic using the url and getting the data
return "data from service";
}

}

A couple of important things to note are as follows:

  • @Component public class SomeDataService: The data service bean is managed by Spring because of the @Component annotation.
  • @Value("${somedataservice.url}"): The value of somedataservice.url will be autowired into the url variable. The url value can be used in the bean methods.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset