Tiee
Tiee

Reputation: 111

How can I get context-path and info.info in a Spring-boot application?

My application is a spring-boot application and I enable the info endpoint. My application.yml content is:

info:
  app:
    name: 'app'
    description: 'app desc'
    version: '1.0'
server:
  port: 8080
  servlet:
    context-path: '/app'

How can I get those information when my server is starting? I'd like to know the port and context-path of my server and the name of my app, etc..

Thanks.

Upvotes: 0

Views: 1486

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16805

We can inject those values into Spring components by using @Value annotation. Example:

@Value("${server.servlet.context-path}")
private String contextPath;

Or we can have a configuration class, where we specify a prefix if we want to read part of the file:

@Configuration
@ConfigurationProperties(prefix = "info.app")
public class AppConfig {
    private String name;
    private String description;
    private String version;

    public String getName() {
        return name;
    }
    // Other getters omitted
}

This class can be injected in other components just like any other Spring bean.

Upvotes: 3

Related Questions