Member-only story
Writing custom endpoints in Spring Actuator
Hello! recently I had to write some custom endpoints using Spring Actuator in a little Spring Boot application, in this short but pragmatic post I will show two ways of writing custom endpoints.
Requirements / Configuration
First of all you need to make sure you have the following dependency in your pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Now we require some slight changes to our application.properties or application.yml, depends on what you are using.
I want to expose all the endpoints, for that I will the following configuration:
management.endpoints.web.exposure.include=*
But you can also expose individual beans:
management.endpoints.web.exposure.include=env,beans,metrics
With the above configuration, you should be able to see something like this if you go to your browser and check localhost:8080/actuator
Or you could also use HTTPie or curl:
HTTPie is really nice because it formats automatically the output :). With curl we had to use jq for that.
Note: If you have Spring Security in your classpath you will need extra configuration.
Using @Endpoint annotation
We simply need to use the @Endpoint annotation along with the @Component annotation to create a Spring-managed component.
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
@Component
@Endpoint(id = "say-hello")
public class SayHello {
@ReadOperation
public String say() {
return "hello world";
}
}