Does Spring Boot Actuator have a Java API?

2020-07-23 05:39发布

We customize the Spring Boot Actuator Info endpoint to include the application version number generated during our Jenkins build. We're using gradle to do this:

if (project.hasProperty('BUILD_NUMBER')) {
    version = "${BUILD_NUMBER}"
} else {
    version = "0.0.1-SNAPSHOT"
}

That works great for adding the version to the /info endpoint, but I'd like to access it when the application starts and print it to the application log.

I'm hoping the values are exposed in some property value (similar to spring.profiles.active) or through a Java API. That way, I could do something like this:

    public class MyApplication{

    public static void main(String[] args) throws Exception {
        SpringApplication.run(MyApplication.class, args);

        ConfigurableEnvironment environment = applicationContext.getEnvironment();

System.out.println(environment.getProperty("spring.fancy.path.to.info.version"));
    }
}

Looking through the docs, I'm not finding a way to access these values easily in code. Has anyone else had luck with this?

标签: spring-boot
1条回答
▲ chillily
2楼-- · 2020-07-23 06:10

To get exactly the same properties of an actuator endpoint that are exposed through the REST endpoints, you can inject in one of your classes an instance of the respective endpoint class. In your case, the "right" endpoint class would be the InfoEndpoint. There are analogous endpoint classes for metrics, health, etc.

The interface has changed a little between Spring Boot 1.5.x and Spring Boot 2.x. So the exact fully qualified class name or read method name may vary based on the Spring Boot version that you are using. In Boot 1.5.x, you can find most of the endpoints in the org.springframework.boot.actuate.endpoint package.

Roughly, this is how you could build a simple component for reading your version property (assuming that the name of the property inside the info endpoint is simply build.version):

@Component
public class VersionAccessor {
    private final InfoEndpoint endpoint;

    @Autowired
    public VersionAccessor(InfoEndpoint endpoint) {
        this.endpoint = endpoint;
    }

    public String getVersion() {
        // Spring Boot 2.x
        return String.valueOf(getValueFromMap(endpoint.info()));

        // Spring Boot 1.x
        return String.valueOf(getValueFromMap(endpoint.invoke()));
    }

    // the info returned from the endpoint may contain nested maps
    // the exact steps for retrieving the right value depends on 
    // the exact property name(s). Here, we assume that we are 
    // interested in the build.version property
    private Object getValueFromMap(Map<String, Object> info) {
        return ((Map<String, Object>) info.get("build")).get("version");
    }

}
查看更多
登录 后发表回答