how can I use external configurations within my Spring application?
package hello.example2.Container
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate
@RestController
class ContainerController {
@RequestMapping("/container/{cid}")
public list(@PathVariable Integer cid) {
def template = new RestTemplate();
def container = template.getForObject("http://localhost:5050/container/" + cid.toString(), Container);
return container;
}
}
I want to replace "http://localhost:5050" with a configuration option (f.e. application.yml or application.properties).
This is my application file (Groovy):
package hello.example2
import groovy.transform.CompileStatic
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Configuration
@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@CompileStatic
class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I tried to set "@Configuration" and "@EnableAutoConfiguration" but to be honest I don't know what they are doing. I'm new to Java/Groovy and the Spring framework (but not to programming in general).
I have read these pages but there is no complete example only snippets:
[2] https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
In your configuration file (application.yml or application.properties) add a new entry:
endpointUrl: http://localhost:5050
Then inject that property in your controller:
@RestController
class ContainerController {
@Value("${endpointUrl}")
private String ednpointUrl;
@RequestMapping("/container/{cid}")
public list(@PathVariable Integer cid) {
def template = new RestTemplate();
def container = template.getForObject(endpointUrl+"/container/" + cid.toString(), Container);
return container;
}
}