
Spring Boot Actuator
- 1.7k installs
- 311 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit
Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services. Use when setting up monito
About
The spring boot actuator skill Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services. Use when setting up monitoring, health checks, or metrics for Spring Boot applications. Documentation covers workflows, commands, and guardrails agents should follow when users invoke this capability. Key documented areas include Deliver production-ready observability for Spring Boot services using Actuator endpoints, probes, and Micrometer integration.; Standardize health, metrics, and diagnostics configuration while delegating deep reference material to `references/`.; Support platform requirements for secure operations, SLO reporting, and incident diagnostics.; Trigger: "enable actuator endpoints" - Bootstrap Actuator for a new or existing Spring Boot service. Reference commands include ```gradle; // Gradle. Use when developers or agents need structured guidance for spring boot actuator tasks with evidence grounded in the bundled SKILL.md rather than generic advice.
- Deliver production-ready observability for Spring Boot services using Actuator endpoints, probes, and Micrometer integra
- Standardize health, metrics, and diagnostics configuration while delegating deep reference material to `references/`.
- Support platform requirements for secure operations, SLO reporting, and incident diagnostics.
- Trigger: "enable actuator endpoints" - Bootstrap Actuator for a new or existing Spring Boot service.
- Trigger: "secure management port" - Apply Spring Security policies to protect management traffic.
Spring Boot Actuator by the numbers
- 1,682 all-time installs (skills.sh)
- +58 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #276 of 4,386 Backend & APIs skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
spring-boot-actuator capabilities & compatibility
- Capabilities
- deliver production ready observability for sprin · standardize health, metrics, and diagnostics con · support platform requirements for secure operati · trigger: "enable actuator endpoints" bootstrap · trigger: "secure management port" apply spring
- Use cases
- planning
What spring-boot-actuator says it does
Deliver production-ready observability for Spring Boot services using Actuator endpoints, probes, and Micrometer integra
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-actuatorAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.7k |
|---|---|
| repo stars | ★ 311 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit ↗ |
How do I handle spring boot actuator tasks with agent guidance?
Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services. Use when setting up monito
Who is it for?
Teams needing documented spring boot actuator workflows.
Skip if: Generic advice without reading bundled docs.
When should I use this skill?
Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services. Use when setting up monito
What you get
Structured workflow from spring boot actuator documentation applied to the user request.
- AuditEventRepository configuration
- authentication audit event pipeline
By the numbers
- Covers three default audit event types: authentication success, failure, and access denied
Files
Spring Boot Actuator Skill
Overview
- Deliver production-ready observability for Spring Boot services using Actuator endpoints, probes, and Micrometer integration.
- Standardize health, metrics, and diagnostics configuration while delegating deep reference material to
references/. - Support platform requirements for secure operations, SLO reporting, and incident diagnostics.
When to Use
- Trigger: "enable actuator endpoints" – Bootstrap Actuator for a new or existing Spring Boot service.
- Trigger: "secure management port" – Apply Spring Security policies to protect management traffic.
- Trigger: "configure health probes" – Define readiness and liveness groups for orchestrators.
- Trigger: "export metrics to prometheus" – Wire Micrometer registries and tune metric exposure.
- Trigger: "debug actuator startup" – Inspect condition evaluations and startup metrics when endpoints are missing or slow.
Quick Start
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>// Gradle
dependencies {
implementation "org.springframework.boot:spring-boot-starter-actuator"
}After adding the dependency, verify endpoints respond:
curl http://localhost:8080/actuator/health
curl http://localhost:8080/actuator/infoInstructions
1. Add Actuator Dependency
Include spring-boot-starter-actuator in your build configuration.
Validate: Restart the service and confirm/actuator/healthand/actuator/inforespond with200 OK.
2. Expose Required Endpoints
- Set
management.endpoints.web.exposure.includeto the precise list or"*"for internal deployments. - Adjust
management.endpoints.web.base-path(e.g.,/management) when the default/actuatorconflicts with routing. - Review detailed endpoint semantics in
references/endpoint-reference.md.
Validate: curl http://localhost:8080/actuator returns the list of exposed endpoints.3. Secure Management Traffic
- Apply an isolated
SecurityFilterChainusingEndpointRequest.toAnyEndpoint()with role-based rules. - Combine
management.server.portwith firewall controls or service mesh policies for operator-only access. - Keep
/actuator/health/**publicly accessible only when required; otherwise enforce authentication.
Validate: Unauthenticated requests to protected endpoints return 401 Unauthorized.4. Configure Health Probes
- Enable
management.endpoint.health.probes.enabled=truefor/health/livenessand/health/readiness. - Group indicators via
management.endpoint.health.group.*to match platform expectations. - Implement custom indicators by extending
HealthIndicatororReactiveHealthContributor; sample implementations inreferences/examples.md#custom-health-indicator.
Validate:/actuator/health/readinessreturnsUPwith all mandatory components before promoting to production.
5. Publish Metrics and Traces
- Activate Micrometer exporters (Prometheus, OTLP, Wavefront, StatsD) via
management.metrics.export.*. - Apply
MeterRegistryCustomizerbeans to addapplication,environment, and business tags for observability correlation. - Surface HTTP request metrics with
server.observation.*configuration when using Spring Boot 3.2+.
Validate: Scrape/actuator/prometheusand confirm required meters (http.server.requests,jvm.memory.used) are present.
6. Enable Diagnostics Tooling
- Turn on
/actuator/startup(Spring Boot 3.5+) and/actuator/conditionsduring incident response to inspect auto-configuration decisions. - Register an
HttpExchangeRepository(e.g.,InMemoryHttpExchangeRepository) before enabling/actuator/httpexchangesfor request auditing. - Consult
references/endpoint-reference.mdfor endpoint behaviors and limits.
Validate:/actuator/startupand/actuator/conditionsreturn valid JSON payloads.
Examples
Basic – Expose health and info safely
management:
endpoints:
web:
exposure:
include: "health,info"
endpoint:
health:
show-details: neverIntermediate – Readiness group with custom indicator
@Component
public class PaymentsGatewayHealth implements HealthIndicator {
private final PaymentsClient client;
public PaymentsGatewayHealth(PaymentsClient client) {
this.client = client;
}
@Override
public Health health() {
boolean reachable = client.ping();
return reachable ? Health.up().withDetail("latencyMs", client.latency()).build()
: Health.down().withDetail("error", "Gateway timeout").build();
}
}management:
endpoint:
health:
probes:
enabled: true
group:
readiness:
include: "readinessState,db,paymentsGateway"
show-details: alwaysAdvanced – Dedicated management port with Prometheus export
management:
server:
port: 9091
ssl:
enabled: true
endpoints:
web:
exposure:
include: "health,info,metrics,prometheus"
base-path: "/management"
metrics:
export:
prometheus:
descriptions: true
step: 30s
endpoint:
health:
show-details: when-authorized
roles: "ENDPOINT_ADMIN"@Configuration
public class ActuatorSecurityConfig {
@Bean
SecurityFilterChain actuatorChain(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(c -> c
.requestMatchers(EndpointRequest.to("health")).permitAll()
.anyRequest().hasRole("ENDPOINT_ADMIN"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
}More end-to-end samples are available in references/examples.md.
Best Practices
- Keep SKILL.md concise and rely on
references/for verbose documentation to conserve context. - Apply the principle of least privilege: expose only required endpoints and restrict sensitive ones.
- Use immutable configuration via profile-specific YAML to align environments.
- Monitor actuator traffic separately to detect scraping abuse or brute-force attempts.
- Automate regression checks by scripting
curlprobes in CI/CD pipelines.
Constraints and Warnings
- Avoid exposing
/actuator/env,/actuator/configprops,/actuator/logfile, and/actuator/heapdumpon public networks. - Do not ship custom health indicators that block event loop threads or exceed 250 ms unless absolutely necessary.
- Ensure Actuator metrics exporters run on supported Micrometer registries; unsupported exporters require custom registry beans.
- Maintain compatibility with Spring Boot 3.5.x conventions; older versions may lack probes and observation features.
- Never expose actuator endpoints without authentication in production environments.
- Health indicators should not perform expensive operations that could impact application performance.
- Be cautious with
/actuator/beansand/actuator/mappingsas they reveal internal application structure.
Reference Materials
- Endpoint quick reference
- Implementation examples
- Official documentation extract
- Auditing with Actuator
- Cloud Foundry integration
- Enabling Actuator features
- HTTP exchange recording
- JMX exposure
- Monitoring and metrics
- Logging configuration
- Metrics exporters
- Observability with Micrometer
- Process and Monitoring
- Tracing
- Scripts directory (
scripts/) reserved for future automation; no runtime dependencies today.
Validation Checklist
- Confirm
mvn spring-boot:runor./gradlew bootRunexposes expected endpoints under/actuator(or custom base path). - Verify
/actuator/health/readinessreturnsUPwith all mandatory components before promoting to production. - Scrape
/actuator/metricsor/actuator/prometheusto ensure required meters (http.server.requests,jvm.memory.used) are present. - Run security scans to validate only intended ports and endpoints are reachable from outside the trusted network.
Auditing with Spring Boot Actuator
Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that publishes events (by default, "authentication success", "failure" and "access denied" exceptions). This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures.
You can enable auditing by providing a bean of type AuditEventRepository in your application's configuration. For convenience, Spring Boot offers an InMemoryAuditEventRepository. InMemoryAuditEventRepository has limited capabilities, and we recommend using it only for development environments. For production environments, consider creating your own alternative AuditEventRepository implementation.
Basic Audit Configuration
In-Memory Audit Repository (Development)
@Configuration
public class AuditConfiguration {
@Bean
public AuditEventRepository auditEventRepository() {
return new InMemoryAuditEventRepository();
}
}Database Audit Repository (Production)
@Entity
@Table(name = "audit_events")
public class PersistentAuditEvent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "principal", nullable = false)
private String principal;
@Column(name = "audit_event_type", nullable = false)
private String auditEventType;
@Column(name = "audit_event_date", nullable = false)
private Instant auditEventDate;
@ElementCollection
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "audit_event_data",
joinColumns = @JoinColumn(name = "event_id"))
private Map<String, String> data = new HashMap<>();
// Constructors, getters, setters
}
@Repository
public class CustomAuditEventRepository implements AuditEventRepository {
private final PersistentAuditEventRepository repository;
public CustomAuditEventRepository(PersistentAuditEventRepository repository) {
this.repository = repository;
}
@Override
public void add(AuditEvent event) {
PersistentAuditEvent persistentEvent = new PersistentAuditEvent();
persistentEvent.setPrincipal(event.getPrincipal());
persistentEvent.setAuditEventType(event.getType());
persistentEvent.setAuditEventDate(event.getTimestamp());
persistentEvent.setData(event.getData());
repository.save(persistentEvent);
}
@Override
public List<AuditEvent> find(String principal, Instant after, String type) {
List<PersistentAuditEvent> events = repository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(
principal, after, type);
return events.stream()
.map(this::convertToAuditEvent)
.collect(Collectors.toList());
}
private AuditEvent convertToAuditEvent(PersistentAuditEvent persistentEvent) {
return new AuditEvent(persistentEvent.getAuditEventDate(),
persistentEvent.getPrincipal(),
persistentEvent.getAuditEventType(),
persistentEvent.getData());
}
}Custom Auditing
Custom Audit Events
You can publish custom audit events using AuditEventRepository:
@Service
public class UserService {
private final AuditEventRepository auditEventRepository;
private final UserRepository userRepository;
public UserService(AuditEventRepository auditEventRepository,
UserRepository userRepository) {
this.auditEventRepository = auditEventRepository;
this.userRepository = userRepository;
}
public User createUser(CreateUserRequest request) {
User user = userRepository.save(request.toUser());
// Publish audit event
Map<String, String> data = new HashMap<>();
data.put("userId", user.getId().toString());
data.put("username", user.getUsername());
data.put("email", user.getEmail());
AuditEvent event = new AuditEvent(getCurrentUsername(), "USER_CREATED", data);
auditEventRepository.add(event);
return user;
}
public void deleteUser(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
userRepository.delete(user);
// Publish audit event
Map<String, String> data = new HashMap<>();
data.put("userId", userId.toString());
data.put("username", user.getUsername());
AuditEvent event = new AuditEvent(getCurrentUsername(), "USER_DELETED", data);
auditEventRepository.add(event);
}
private String getCurrentUsername() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getName() : "system";
}
}Custom Audit Event Publisher
@Component
public class AuditEventPublisher {
private final AuditEventRepository auditEventRepository;
public AuditEventPublisher(AuditEventRepository auditEventRepository) {
this.auditEventRepository = auditEventRepository;
}
public void publishEvent(String type, Map<String, String> data) {
String principal = getCurrentPrincipal();
AuditEvent event = new AuditEvent(principal, type, data);
auditEventRepository.add(event);
}
public void publishSecurityEvent(String type, String details) {
Map<String, String> data = new HashMap<>();
data.put("details", details);
data.put("timestamp", Instant.now().toString());
data.put("source", "security");
publishEvent(type, data);
}
public void publishBusinessEvent(String type, String entityId, String action) {
Map<String, String> data = new HashMap<>();
data.put("entityId", entityId);
data.put("action", action);
data.put("timestamp", Instant.now().toString());
publishEvent(type, data);
}
private String getCurrentPrincipal() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getName() : "anonymous";
}
}Method-Level Auditing
Using AOP for Automatic Auditing
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Auditable {
String value() default "";
String type() default "";
boolean includeArgs() default false;
boolean includeResult() default false;
}
@Aspect
@Component
public class AuditableAspect {
private final AuditEventPublisher auditEventPublisher;
public AuditableAspect(AuditEventPublisher auditEventPublisher) {
this.auditEventPublisher = auditEventPublisher;
}
@Around("@annotation(auditable)")
public Object auditMethod(ProceedingJoinPoint joinPoint, Auditable auditable) throws Throwable {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
String auditType = auditable.type().isEmpty() ?
className + "." + methodName : auditable.type();
Map<String, String> data = new HashMap<>();
data.put("method", methodName);
data.put("class", className);
if (auditable.includeArgs()) {
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
data.put("arg" + i, String.valueOf(args[i]));
}
}
try {
Object result = joinPoint.proceed();
if (auditable.includeResult() && result != null) {
data.put("result", String.valueOf(result));
}
data.put("status", "success");
auditEventPublisher.publishEvent(auditType, data);
return result;
} catch (Exception ex) {
data.put("status", "failure");
data.put("error", ex.getMessage());
auditEventPublisher.publishEvent(auditType, data);
throw ex;
}
}
}Usage Example
@Service
public class OrderService {
@Auditable(type = "ORDER_CREATED", includeArgs = true)
public Order createOrder(CreateOrderRequest request) {
// Order creation logic
return new Order();
}
@Auditable(type = "ORDER_CANCELLED", includeResult = true)
public Order cancelOrder(Long orderId) {
// Order cancellation logic
return cancelledOrder;
}
@Auditable(type = "PAYMENT_PROCESSED")
public PaymentResult processPayment(PaymentRequest request) {
// Payment processing logic
return new PaymentResult();
}
}Security Audit Events
Authentication Events
Spring Boot automatically publishes authentication events when using Spring Security:
AUTHENTICATION_SUCCESSAUTHENTICATION_FAILUREACCESS_DENIED
Custom Security Events
@Component
public class SecurityAuditService {
private final AuditEventPublisher auditEventPublisher;
public SecurityAuditService(AuditEventPublisher auditEventPublisher) {
this.auditEventPublisher = auditEventPublisher;
}
@EventListener
public void handleAuthenticationSuccess(AuthenticationSuccessEvent event) {
Map<String, String> data = new HashMap<>();
data.put("username", event.getAuthentication().getName());
data.put("authorities", event.getAuthentication().getAuthorities().toString());
data.put("source", getClientIP());
auditEventPublisher.publishEvent("AUTHENTICATION_SUCCESS", data);
}
@EventListener
public void handleAuthenticationFailure(AbstractAuthenticationFailureEvent event) {
Map<String, String> data = new HashMap<>();
data.put("username", event.getAuthentication().getName());
data.put("exception", event.getException().getClass().getSimpleName());
data.put("message", event.getException().getMessage());
data.put("source", getClientIP());
auditEventPublisher.publishEvent("AUTHENTICATION_FAILURE", data);
}
@EventListener
public void handleAccessDenied(AuthorizationDeniedEvent event) {
Map<String, String> data = new HashMap<>();
data.put("username", event.getAuthentication().getName());
data.put("resource", event.getAuthorizationDecision().toString());
data.put("source", getClientIP());
auditEventPublisher.publishEvent("ACCESS_DENIED", data);
}
private String getClientIP() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
return request.getRemoteAddr();
}
return "unknown";
}
}Password Change Auditing
@Service
public class PasswordService {
private final AuditEventPublisher auditEventPublisher;
private final PasswordEncoder passwordEncoder;
public PasswordService(AuditEventPublisher auditEventPublisher,
PasswordEncoder passwordEncoder) {
this.auditEventPublisher = auditEventPublisher;
this.passwordEncoder = passwordEncoder;
}
public void changePassword(String oldPassword, String newPassword) {
String username = getCurrentUsername();
try {
// Validate old password
if (!isCurrentPassword(oldPassword)) {
Map<String, String> data = new HashMap<>();
data.put("username", username);
data.put("reason", "invalid_old_password");
auditEventPublisher.publishEvent("PASSWORD_CHANGE_FAILED", data);
throw new InvalidPasswordException("Invalid old password");
}
// Change password
updatePassword(newPassword);
// Audit success
Map<String, String> data = new HashMap<>();
data.put("username", username);
auditEventPublisher.publishEvent("PASSWORD_CHANGED", data);
} catch (Exception ex) {
Map<String, String> data = new HashMap<>();
data.put("username", username);
data.put("error", ex.getMessage());
auditEventPublisher.publishEvent("PASSWORD_CHANGE_ERROR", data);
throw ex;
}
}
private boolean isCurrentPassword(String password) {
// Implementation
return true;
}
private void updatePassword(String newPassword) {
// Implementation
}
private String getCurrentUsername() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getName() : "anonymous";
}
}Audit Events Endpoint
The /actuator/auditevents endpoint exposes audit events:
GET /actuator/auditevents
GET /actuator/auditevents?principal=user&after=2023-01-01T00:00:00Z&type=USER_CREATEDResponse format:
{
"events": [
{
"timestamp": "2023-12-01T10:30:00Z",
"principal": "admin",
"type": "USER_CREATED",
"data": {
"userId": "123",
"username": "newuser",
"email": "user@example.com"
}
}
]
}Production Configuration
Secure Audit Endpoint
@Configuration
public class AuditSecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain auditSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.to("auditevents"))
.authorizeHttpRequests(requests ->
requests.anyRequest().hasRole("AUDITOR"))
.httpBasic(withDefaults())
.build();
}
}Audit Configuration
management:
endpoint:
auditevents:
enabled: true
cache:
time-to-live: 10s
endpoints:
web:
exposure:
include: "auditevents"
# Custom audit properties
audit:
retention-days: 90
max-events-per-request: 100
sensitive-data-masking: trueBest Practices
1. Data Sensitivity: Never include sensitive data (passwords, tokens) in audit events 2. Performance: Consider async processing for high-volume audit events 3. Retention: Implement audit data retention policies 4. Security: Secure the audit endpoint and audit data storage 5. Monitoring: Monitor audit system health and performance 6. Compliance: Ensure audit events meet regulatory requirements 7. Immutability: Ensure audit events cannot be modified after creation
Async Audit Processing
@Configuration
@EnableAsync
public class AsyncAuditConfiguration {
@Bean
public TaskExecutor auditTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("audit-");
executor.initialize();
return executor;
}
}
@Service
public class AsyncAuditEventRepository implements AuditEventRepository {
private final AuditEventRepository delegate;
public AsyncAuditEventRepository(AuditEventRepository delegate) {
this.delegate = delegate;
}
@Override
@Async("auditTaskExecutor")
public void add(AuditEvent event) {
delegate.add(event);
}
@Override
public List<AuditEvent> find(String principal, Instant after, String type) {
return delegate.find(principal, after, type);
}
}Cloud Foundry Support
Spring Boot Actuator includes additional support when you deploy to a compatible Cloud Foundry instance. The /cloudfoundryapplication path provides an alternative secured route to all @Endpoint beans.
Cloud Foundry Configuration
When running on Cloud Foundry, Spring Boot automatically configures:
- Cloud Foundry-specific health indicators
- Cloud Foundry application information
- Secure endpoint access through Cloud Foundry's security model
Basic Configuration
management:
cloudfoundry:
enabled: true
endpoints:
web:
exposure:
include: "*"Cloud Foundry Health
@Component
public class CloudFoundryHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// Cloud Foundry specific health checks
return Health.up()
.withDetail("cloud-foundry", "available")
.withDetail("instance-index", System.getenv("CF_INSTANCE_INDEX"))
.withDetail("application-id", System.getenv("VCAP_APPLICATION"))
.build();
}
}Best Practices
1. Security: Use Cloud Foundry's built-in security for actuator endpoints 2. Service Binding: Leverage VCAP_SERVICES for automatic configuration 3. Health Checks: Configure appropriate health endpoints for load balancer checks 4. Metrics: Export metrics to Cloud Foundry monitoring systems
Enabling Actuator
The spring-boot-actuator module provides all of Spring Boot's production-ready features. The recommended way to enable the features is to add a dependency on the spring-boot-starter-actuator starter.
Definition of Actuator
>
An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change.
Adding the Actuator Dependency
To add the actuator to a Maven-based project, add the following starter dependency:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>For Gradle, use the following declaration:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
}Endpoint Reference
This document provides a comprehensive reference for all available Spring Boot Actuator endpoints.
Built-in Endpoints
| Endpoint | HTTP Method | Description | Default Exposure |
|---|---|---|---|
auditevents | GET | Audit events for the application | JMX |
beans | GET | Complete list of Spring beans | JMX |
caches | GET, DELETE | Available caches | JMX |
conditions | GET | Configuration and auto-configuration conditions | JMX |
configprops | GET | Configuration properties | JMX |
env | GET, POST | Environment properties | JMX |
flyway | GET | Flyway database migrations | JMX |
health | GET | Application health information | Web, JMX |
heapdump | GET | Heap dump | JMX |
httpexchanges | GET | HTTP exchange information | JMX |
info | GET | Application information | Web, JMX |
integrationgraph | GET | Spring Integration graph | JMX |
logfile | GET | Application log file | JMX |
loggers | GET, POST | Logger configuration | JMX |
liquibase | GET | Liquibase database migrations | JMX |
mappings | GET | Request mapping information | JMX |
metrics | GET | Application metrics | JMX |
prometheus | GET | Prometheus metrics | None |
quartz | GET | Quartz scheduler information | JMX |
scheduledtasks | GET | Scheduled tasks | JMX |
sessions | GET, DELETE | User sessions | JMX |
shutdown | POST | Graceful application shutdown | JMX |
startup | GET | Application startup information | JMX |
threaddump | GET | Thread dump | JMX |
Endpoint URLs
Web Endpoints
- Base path:
/actuator - Example:
GET /actuator/health - Custom base path:
management.endpoints.web.base-path
JMX Endpoints
- Domain:
org.springframework.boot - Example:
org.springframework.boot:type=Endpoint,name=Health
Endpoint Configuration
Global Configuration
management:
endpoints:
enabled-by-default: true
web:
exposure:
include: "health,info,metrics"
exclude: "env,beans"
base-path: "/actuator"
path-mapping:
health: "status"
jmx:
exposure:
include: "*"Individual Endpoint Configuration
management:
endpoint:
health:
enabled: true
show-details: when-authorized
show-components: always
cache:
time-to-live: 10s
metrics:
enabled: true
cache:
time-to-live: 0s
info:
enabled: trueSecurity Configuration
Web Security
@Configuration
public class ActuatorSecurityConfiguration {
@Bean
@Order(1)
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(requests ->
requests
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
.anyRequest().hasRole("ACTUATOR")
)
.httpBasic(withDefaults())
.build();
}
}Method-level Security
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/actuator/shutdown")
public Object shutdown() {
// Shutdown logic
}Custom Endpoints
Creating Custom Endpoints
@Component
@Endpoint(id = "custom")
public class CustomEndpoint {
@ReadOperation
public Map<String, Object> customEndpoint() {
return Map.of("custom", "data");
}
@WriteOperation
public void writeOperation(@Selector String name, String value) {
// Write operation
}
@DeleteOperation
public void deleteOperation(@Selector String name) {
// Delete operation
}
}Web-specific Endpoints
@Component
@WebEndpoint(id = "web-custom")
public class WebCustomEndpoint {
@ReadOperation
public WebEndpointResponse<Map<String, Object>> webCustomEndpoint() {
Map<String, Object> data = Map.of("web", "specific");
return new WebEndpointResponse<>(data, 200);
}
}Best Practices
1. Security: Always secure actuator endpoints in production 2. Exposure: Only expose necessary endpoints 3. Performance: Configure appropriate caching for endpoints 4. Monitoring: Monitor actuator endpoint usage 5. Documentation: Document custom endpoints thoroughly
Actuator Endpoints
Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the health endpoint provides basic application health information.
You can control access to each individual endpoint and expose them (make them remotely accessible) over HTTP or JMX. An endpoint is considered to be available when access to it is permitted and it is exposed. The built-in endpoints are auto-configured only when they are available. Most applications choose exposure over HTTP, where the ID of the endpoint and a prefix of /actuator is mapped to a URL. For example, by default, the health endpoint is mapped to /actuator/health.
TIP
>
To learn more about the Actuator's endpoints and their request and response formats, see the Spring Boot Actuator API documentation.
Available Endpoints
The following technology-agnostic endpoints are available:
| ID | Description |
|---|---|
auditevents | Exposes audit events information for the current application. Requires an AuditEventRepository bean. |
beans | Displays a complete list of all the Spring beans in your application. |
caches | Exposes available caches. |
conditions | Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match. |
configprops | Displays a collated list of all @ConfigurationProperties. Subject to sanitization. |
env | Exposes properties from Spring's ConfigurableEnvironment. Subject to sanitization. |
flyway | Shows any Flyway database migrations that have been applied. Requires one or more Flyway beans. |
health | Shows application health information. |
httpexchanges | Displays HTTP exchange information (by default, the last 100 HTTP request-response exchanges). Requires an HttpExchangeRepository bean. |
info | Displays arbitrary application info. |
integrationgraph | Shows the Spring Integration graph. Requires a dependency on spring-integration-core. |
loggers | Shows and modifies the configuration of loggers in the application. |
liquibase | Shows any Liquibase database migrations that have been applied. Requires one or more Liquibase beans. |
metrics | Shows metrics information for the current application. |
mappings | Displays a collated list of all @RequestMapping paths. |
quartz | Shows information about Quartz Scheduler jobs. Subject to sanitization. |
scheduledtasks | Displays the scheduled tasks in your application. |
sessions | Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Requires a servlet-based web application that uses Spring Session. |
shutdown | Lets the application be gracefully shutdown. Only works when using jar packaging. Disabled by default. |
startup | Shows the startup steps data collected by the ApplicationStartup. Requires the SpringApplication to be configured with a BufferingApplicationStartup. |
threaddump | Performs a thread dump. |
If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints:
| ID | Description |
|---|---|
heapdump | Returns a heap dump file. On a HotSpot JVM, an HPROF-format file is returned. On an OpenJ9 JVM, a PHD-format file is returned. |
logfile | Returns the contents of the logfile (if the logging.file.name or the logging.file.path property has been set). Supports the use of the HTTP Range header to retrieve part of the log file's content. |
prometheus | Exposes metrics in a format that can be scraped by a Prometheus server. Requires a dependency on micrometer-registry-prometheus. |
Controlling Access to Endpoints
By default, access to all endpoints except for shutdown and heapdump is unrestricted. To configure the permitted access to an endpoint, use its management.endpoint.<id>.access property. The following example allows unrestricted access to the shutdown endpoint:
management:
endpoint:
shutdown:
access: unrestrictedIf you prefer access to be opt-in rather than opt-out, set the management.endpoints.access.default property to none and use individual endpoint access properties to opt back in. The following example allows read-only access to the loggers endpoint and denies access to all other endpoints:
management:
endpoints:
access:
default: none
endpoint:
loggers:
access: read-onlyNOTE
>
Inaccessible endpoints are removed entirely from the application context. If you want to change only the technologies over which an endpoint is exposed, use theincludeandexcludeproperties instead.
Limiting Access
Application-wide endpoint access can be limited using the management.endpoints.access.max-permitted property. This property takes precedence over the default access or an individual endpoint's access level. Set it to none to make all endpoints inaccessible. Set it to read-only to only allow read access to endpoints.
For @Endpoint, @JmxEndpoint, and @WebEndpoint, read access equates to the endpoint methods annotated with @ReadOperation. For @ControllerEndpoint and @RestControllerEndpoint, read access equates to HTTP GET requests.
Exposing Endpoints
By default, only the health endpoint is exposed over HTTP and JMX. To configure which endpoints are exposed, use the include and exclude properties:
management:
endpoints:
web:
exposure:
include: "health,info,metrics"
exclude: "beans"The include property lists the IDs of the endpoints that are exposed. The exclude property lists the IDs of the endpoints that should not be exposed. The exclude property takes precedence over the include property.
To expose all endpoints over HTTP:
management:
endpoints:
web:
exposure:
include: "*"Security
For security purposes, only the /health endpoint is exposed over HTTP by default. You can use the management.endpoints.web.exposure.include property to configure the endpoints that are exposed.
If Spring Security is on the classpath and no other WebSecurityConfigurer bean is present, all actuators other than /health are secured by Spring Boot auto-configuration. If you define a custom WebSecurityConfigurer bean, Spring Boot auto-configuration backs off and lets you fully control the actuator access rules.
Custom Endpoints
You can add additional endpoints by using @Endpoint and @Component annotations:
@Component
@Endpoint(id = "custom")
public class CustomEndpoint {
@ReadOperation
public String customEndpoint() {
return "Custom endpoint response";
}
}Web Endpoints
For web-specific endpoints, use @WebEndpoint:
@Component
@WebEndpoint(id = "web-custom")
public class WebCustomEndpoint {
@ReadOperation
public String webCustomEndpoint() {
return "Web custom endpoint response";
}
}JMX Endpoints
For JMX-specific endpoints, use @JmxEndpoint:
@Component
@JmxEndpoint(id = "jmx-custom")
public class JmxCustomEndpoint {
@ReadOperation
public String jmxCustomEndpoint() {
return "JMX custom endpoint response";
}
}Health Endpoint
The health endpoint provides detailed information about the health of the application. By default, only health status is shown to unauthenticated users:
{
"status": "UP"
}To show detailed health information:
management:
endpoint:
health:
show-details: alwaysCustom Health Indicators
You can provide custom health information by registering Spring beans that implement the HealthIndicator interface:
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// Perform custom health check
boolean isHealthy = checkHealth();
if (isHealthy) {
return Health.up()
.withDetail("custom", "Service is running")
.build();
} else {
return Health.down()
.withDetail("custom", "Service is down")
.build();
}
}
private boolean checkHealth() {
// Custom health check logic
return true;
}
}Info Endpoint
The info endpoint publishes information about your application. You can customize this information by implementing InfoContributor:
@Component
public class CustomInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("custom", "Custom application info");
}
}Git Information
To expose git information in the info endpoint, add the following to your build:
Maven:
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>Gradle:
plugins {
id "com.gorylenko.gradle-git-properties" version "2.4.1"
}Build Information
Build information can be added to the info endpoint by configuring the build plugins:
Maven:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>Gradle:
springBoot {
buildInfo()
}Metrics Endpoint
The metrics endpoint provides access to application metrics collected by Micrometer. You can view all available metrics:
GET /actuator/metricsOr view a specific metric:
GET /actuator/metrics/jvm.memory.usedCustom Metrics
You can add custom metrics using Micrometer:
@Component
public class CustomMetrics {
private final Counter customCounter;
private final Timer customTimer;
public CustomMetrics(MeterRegistry meterRegistry) {
this.customCounter = Counter.builder("custom.requests")
.description("Custom request counter")
.register(meterRegistry);
this.customTimer = Timer.builder("custom.processing.time")
.description("Custom processing time")
.register(meterRegistry);
}
public void incrementCounter() {
customCounter.increment();
}
public void recordTime(Duration duration) {
customTimer.record(duration);
}
}Environment Endpoint
The env endpoint exposes properties from the Spring Environment. This includes configuration properties, system properties, environment variables, and more.
To view a specific property:
GET /actuator/env/server.portLoggers Endpoint
The loggers endpoint shows and allows modification of logger levels in your application.
To view all loggers:
GET /actuator/loggersTo view a specific logger:
GET /actuator/loggers/com.example.MyClassTo change a logger level:
POST /actuator/loggers/com.example.MyClass
Content-Type: application/json
{
"configuredLevel": "DEBUG"
}Configuration Properties Endpoint
The configprops endpoint displays all @ConfigurationProperties in your application:
GET /actuator/configpropsProperties that may contain sensitive information are masked by default.
Thread Dump Endpoint
The threaddump endpoint provides a thread dump of the application:
GET /actuator/threaddumpThis is useful for diagnosing performance issues and detecting deadlocks.
Shutdown Endpoint
The shutdown endpoint allows you to gracefully shut down the application. It's disabled by default for security reasons:
management:
endpoint:
shutdown:
enabled: trueTo trigger shutdown:
POST /actuator/shutdownWARNING
>
The shutdown endpoint should be secured in production environments as it can terminate the application.
Spring Boot Actuator Examples
Complete Application Example
Application Configuration
@SpringBootApplication
public class MonitoringApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MonitoringApplication.class);
// Enable startup tracking
app.setApplicationStartup(new BufferingApplicationStartup(2048));
app.run(args);
}
@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config()
.commonTags("application", "order-service", "environment", "production");
}
}Application Properties
spring:
application:
name: order-service
info:
app:
name: ${spring.application.name}
description: Order Processing Service
version: "@project.version@"
encoding: "@project.build.sourceEncoding@"
java:
version: "@java.version@"
management:
endpoints:
web:
exposure:
include: "health,info,metrics,prometheus,startup"
base-path: "/actuator"
endpoint:
health:
show-details: when-authorized
show-components: always
probes:
enabled: true
group:
liveness:
include: "ping,diskSpace"
readiness:
include: "readinessState,db,redis,externalApi"
show-details: always
status:
order: "fatal,down,out-of-service,warning,unknown,up"
http-mapping:
down: 503
fatal: 503
warning: 500
info:
enabled: true
metrics:
enabled: true
metrics:
export:
prometheus:
enabled: true
tags:
application: ${spring.application.name}
region: eu-west-1
info:
git:
mode: full
build:
enabled: trueHealth Indicators Examples
Database Health Indicator
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
private static final Logger log = LoggerFactory.getLogger(DatabaseHealthIndicator.class);
private final DataSource dataSource;
public DatabaseHealthIndicator(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Health health() {
try (Connection connection = dataSource.getConnection()) {
long startTime = System.currentTimeMillis();
boolean valid = connection.isValid(1000);
long responseTime = System.currentTimeMillis() - startTime;
if (!valid) {
return Health.down()
.withDetail("database", "Connection not valid")
.build();
}
DatabaseMetaData metaData = connection.getMetaData();
Health.Builder builder = Health.up()
.withDetail("database", metaData.getDatabaseProductName())
.withDetail("version", metaData.getDatabaseProductVersion())
.withDetail("responseTime", responseTime + "ms");
if (responseTime > 500) {
builder.status("WARNING")
.withDetail("warning", "Slow database connection");
}
return builder.build();
} catch (SQLException ex) {
log.error("Database health check failed", ex);
return Health.down()
.withDetail("error", ex.getMessage())
.withException(ex)
.build();
}
}
}External API Health Indicator with Circuit Breaker
@Component
public class PaymentGatewayHealthIndicator implements HealthIndicator {
private final RestTemplate restTemplate;
private final CircuitBreaker circuitBreaker;
public PaymentGatewayHealthIndicator(
RestTemplate restTemplate,
@Qualifier("paymentCircuitBreaker") CircuitBreaker circuitBreaker) {
this.restTemplate = restTemplate;
this.circuitBreaker = circuitBreaker;
}
@Override
public Health health() {
CircuitBreaker.State state = circuitBreaker.getState();
Health.Builder builder = Health.up()
.withDetail("circuitBreaker", state.toString())
.withDetail("service", "Payment Gateway");
if (state == CircuitBreaker.State.OPEN) {
return builder
.down()
.withDetail("reason", "Circuit breaker is open")
.build();
}
if (state == CircuitBreaker.State.HALF_OPEN) {
builder.status("WARNING")
.withDetail("reason", "Circuit breaker is testing");
}
try {
long startTime = System.currentTimeMillis();
ResponseEntity<Map> response = restTemplate.getForEntity(
"https://api.payment.com/health",
Map.class
);
long responseTime = System.currentTimeMillis() - startTime;
return builder
.withDetail("responseTime", responseTime + "ms")
.withDetail("statusCode", response.getStatusCode().value())
.build();
} catch (Exception ex) {
return builder
.down()
.withDetail("error", ex.getMessage())
.build();
}
}
}Cache Health Indicator
@Component
public class CacheHealthIndicator implements HealthIndicator {
private final CacheManager cacheManager;
public CacheHealthIndicator(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Override
public Health health() {
Collection<String> cacheNames = cacheManager.getCacheNames();
Map<String, Object> cacheDetails = new HashMap<>();
boolean allHealthy = true;
for (String cacheName : cacheNames) {
Cache cache = cacheManager.getCache(cacheName);
if (cache != null) {
try {
// Test cache operations
cache.put("health-check", "test");
String value = cache.get("health-check", String.class);
cache.evict("health-check");
cacheDetails.put(cacheName, "UP");
} catch (Exception ex) {
cacheDetails.put(cacheName, "DOWN: " + ex.getMessage());
allHealthy = false;
}
}
}
Health.Builder builder = allHealthy ? Health.up() : Health.down();
return builder
.withDetail("caches", cacheDetails)
.withDetail("totalCaches", cacheNames.size())
.build();
}
}Reactive Health Indicator
@Component
public class ReactiveExternalServiceHealthIndicator implements ReactiveHealthIndicator {
private final WebClient webClient;
public ReactiveExternalServiceHealthIndicator(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder
.baseUrl("https://api.example.com")
.build();
}
@Override
public Mono<Health> health() {
return webClient
.get()
.uri("/health")
.retrieve()
.toBodilessEntity()
.map(response -> Health.up()
.withDetail("statusCode", response.getStatusCode().value())
.withDetail("service", "External API")
.build())
.timeout(Duration.ofSeconds(2))
.onErrorResume(TimeoutException.class, ex ->
Mono.just(Health.down()
.withDetail("error", "Timeout after 2 seconds")
.build()))
.onErrorResume(ex ->
Mono.just(Health.down()
.withDetail("error", ex.getMessage())
.build()));
}
}Custom Endpoints Examples
Application Statistics Endpoint
@Component
@Endpoint(id = "appstats")
public class AppStatisticsEndpoint {
private final UserRepository userRepository;
private final OrderRepository orderRepository;
private final MeterRegistry meterRegistry;
public AppStatisticsEndpoint(
UserRepository userRepository,
OrderRepository orderRepository,
MeterRegistry meterRegistry) {
this.userRepository = userRepository;
this.orderRepository = orderRepository;
this.meterRegistry = meterRegistry;
}
@ReadOperation
public Map<String, Object> getStatistics() {
Map<String, Object> stats = new HashMap<>();
// User statistics
stats.put("users", Map.of(
"total", userRepository.count(),
"active", userRepository.countByStatus("ACTIVE"),
"inactive", userRepository.countByStatus("INACTIVE")
));
// Order statistics
stats.put("orders", Map.of(
"total", orderRepository.count(),
"pending", orderRepository.countByStatus("PENDING"),
"completed", orderRepository.countByStatus("COMPLETED"),
"cancelled", orderRepository.countByStatus("CANCELLED")
));
// JVM statistics
stats.put("jvm", Map.of(
"memoryUsed", getMetricValue("jvm.memory.used"),
"memoryMax", getMetricValue("jvm.memory.max"),
"threadCount", getMetricValue("jvm.threads.live")
));
stats.put("timestamp", Instant.now());
return stats;
}
@ReadOperation
public Map<String, Object> getStatisticsByType(@Selector String type) {
return switch (type.toLowerCase()) {
case "users" -> Map.of(
"total", userRepository.count(),
"byStatus", userRepository.countByStatusGrouped()
);
case "orders" -> Map.of(
"total", orderRepository.count(),
"byStatus", orderRepository.countByStatusGrouped()
);
default -> Map.of("error", "Unknown type: " + type);
};
}
private Double getMetricValue(String meterName) {
return meterRegistry.find(meterName)
.gauge()
.map(Gauge::value)
.orElse(0.0);
}
}Feature Flags Endpoint
@Component
@Endpoint(id = "features")
public class FeatureFlagsEndpoint {
private final Map<String, FeatureFlag> features = new ConcurrentHashMap<>();
private final ApplicationEventPublisher eventPublisher;
public FeatureFlagsEndpoint(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
initializeDefaultFeatures();
}
private void initializeDefaultFeatures() {
features.put("dark-mode", new FeatureFlag(true, "Dark mode UI"));
features.put("new-checkout", new FeatureFlag(false, "New checkout flow"));
features.put("ai-recommendations", new FeatureFlag(false, "AI-powered recommendations"));
}
@ReadOperation
public Map<String, FeatureFlag> getAllFeatures() {
return features;
}
@ReadOperation
public FeatureFlag getFeature(@Selector String name) {
return features.get(name);
}
@WriteOperation
public void updateFeature(
@Selector String name,
@Nullable Boolean enabled,
@Nullable String description) {
features.compute(name, (key, existing) -> {
if (existing == null) {
existing = new FeatureFlag(false, "");
}
if (enabled != null) {
existing.setEnabled(enabled);
}
if (description != null) {
existing.setDescription(description);
}
return existing;
});
eventPublisher.publishEvent(new FeatureFlagChangedEvent(name, features.get(name)));
}
@DeleteOperation
public void deleteFeature(@Selector String name) {
FeatureFlag removed = features.remove(name);
if (removed != null) {
eventPublisher.publishEvent(new FeatureFlagDeletedEvent(name));
}
}
public static class FeatureFlag {
private boolean enabled;
private String description;
private Instant lastModified = Instant.now();
public FeatureFlag() {}
public FeatureFlag(boolean enabled, String description) {
this.enabled = enabled;
this.description = description;
}
// Getters and setters
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) {
this.enabled = enabled;
this.lastModified = Instant.now();
}
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Instant getLastModified() { return lastModified; }
}
}Cache Management Endpoint
@Component
@Endpoint(id = "caches")
public class CacheManagementEndpoint {
private final CacheManager cacheManager;
public CacheManagementEndpoint(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@ReadOperation
public Map<String, Object> getCaches() {
Collection<String> cacheNames = cacheManager.getCacheNames();
Map<String, Object> result = new HashMap<>();
result.put("totalCaches", cacheNames.size());
result.put("caches", cacheNames);
return result;
}
@ReadOperation
public Map<String, Object> getCache(@Selector String cacheName) {
Cache cache = cacheManager.getCache(cacheName);
if (cache == null) {
return Map.of("error", "Cache not found: " + cacheName);
}
return Map.of(
"name", cacheName,
"type", cache.getClass().getSimpleName()
);
}
@DeleteOperation
public void clearCache(@Selector String cacheName) {
Cache cache = cacheManager.getCache(cacheName);
if (cache != null) {
cache.clear();
}
}
@WriteOperation
public void clearAllCaches() {
cacheManager.getCacheNames()
.forEach(name -> {
Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.clear();
}
});
}
}Custom Info Contributors
Detailed Application Info
@Component
public class DetailedApplicationInfoContributor implements InfoContributor {
private final Environment environment;
private final UserRepository userRepository;
private final OrderRepository orderRepository;
public DetailedApplicationInfoContributor(
Environment environment,
UserRepository userRepository,
OrderRepository orderRepository) {
this.environment = environment;
this.userRepository = userRepository;
this.orderRepository = orderRepository;
}
@Override
public void contribute(Info.Builder builder) {
// Runtime information
Runtime runtime = Runtime.getRuntime();
builder.withDetail("runtime", Map.of(
"processors", runtime.availableProcessors(),
"freeMemory", runtime.freeMemory(),
"totalMemory", runtime.totalMemory(),
"maxMemory", runtime.maxMemory(),
"uptime", ManagementFactory.getRuntimeMXBean().getUptime()
));
// Active profiles
builder.withDetail("profiles", List.of(environment.getActiveProfiles()));
// Database statistics
builder.withDetail("database", Map.of(
"users", Map.of(
"total", userRepository.count(),
"active", userRepository.countByStatus("ACTIVE")
),
"orders", Map.of(
"total", orderRepository.count(),
"pending", orderRepository.countByStatus("PENDING"),
"completed", orderRepository.countByStatus("COMPLETED")
)
));
// Deployment information
builder.withDetail("deployment", Map.of(
"environment", environment.getProperty("app.environment", "unknown"),
"region", environment.getProperty("app.region", "unknown"),
"instance", getHostname()
));
}
private String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
return "unknown";
}
}
}Dependency Version Info
@Component
public class DependencyVersionInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
Map<String, String> versions = new HashMap<>();
// Spring versions
versions.put("spring-boot", SpringBootVersion.getVersion());
versions.put("spring-framework", SpringVersion.getVersion());
// Java version
versions.put("java", System.getProperty("java.version"));
versions.put("java-vendor", System.getProperty("java.vendor"));
// Other dependencies (if available)
addVersionIfPresent(versions, "hibernate", "org.hibernate.Version", "getVersionString");
addVersionIfPresent(versions, "jackson", "com.fasterxml.jackson.core.Version", "versionString");
builder.withDetail("dependencies", versions);
}
private void addVersionIfPresent(Map<String, String> versions, String key,
String className, String methodName) {
try {
Class<?> clazz = Class.forName(className);
Object versionInstance = clazz.getDeclaredConstructor().newInstance();
String version = (String) clazz.getMethod(methodName).invoke(versionInstance);
versions.put(key, version);
} catch (Exception e) {
// Dependency not present or version not accessible
}
}
}Metrics Examples
Service Metrics
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final MeterRegistry meterRegistry;
private final Counter orderCreatedCounter;
private final Counter orderFailedCounter;
private final Timer orderProcessingTimer;
private final DistributionSummary orderAmountSummary;
public OrderService(OrderRepository orderRepository, MeterRegistry meterRegistry) {
this.orderRepository = orderRepository;
this.meterRegistry = meterRegistry;
// Counters
this.orderCreatedCounter = Counter.builder("orders.created")
.description("Total number of orders created")
.tag("service", "order")
.register(meterRegistry);
this.orderFailedCounter = Counter.builder("orders.failed")
.description("Total number of failed orders")
.tag("service", "order")
.register(meterRegistry);
// Timer for processing duration
this.orderProcessingTimer = Timer.builder("order.processing.time")
.description("Order processing duration")
.publishPercentiles(0.5, 0.95, 0.99)
.register(meterRegistry);
// Distribution summary for order amounts
this.orderAmountSummary = DistributionSummary.builder("order.amount")
.description("Order amount distribution")
.baseUnit("EUR")
.publishPercentiles(0.5, 0.95, 0.99)
.register(meterRegistry);
// Gauge for pending orders
Gauge.builder("orders.pending", orderRepository, repo -> repo.countByStatus("PENDING"))
.description("Number of pending orders")
.register(meterRegistry);
}
public Order createOrder(OrderRequest request) {
return orderProcessingTimer.record(() -> {
try {
Order order = processOrder(request);
orderCreatedCounter.increment();
orderAmountSummary.record(order.getTotalAmount());
// Tag by payment method
Counter.builder("orders.created.by.payment")
.tag("paymentMethod", order.getPaymentMethod())
.register(meterRegistry)
.increment();
return order;
} catch (Exception ex) {
orderFailedCounter.increment();
throw ex;
}
});
}
private Order processOrder(OrderRequest request) {
// Implementation
return new Order();
}
}Custom Metrics with Tags
@Service
public class MetricsService {
private final MeterRegistry registry;
public MetricsService(MeterRegistry registry) {
this.registry = registry;
}
public void recordHttpRequest(String method, String endpoint, int statusCode, long duration) {
Timer.builder("http.requests")
.tag("method", method)
.tag("endpoint", endpoint)
.tag("status", String.valueOf(statusCode))
.register(registry)
.record(duration, TimeUnit.MILLISECONDS);
}
public void recordDatabaseQuery(String query, long duration, boolean success) {
Timer.builder("db.queries")
.tag("query", query)
.tag("success", String.valueOf(success))
.register(registry)
.record(duration, TimeUnit.MILLISECONDS);
}
public void trackCacheHit(String cacheName, boolean hit) {
Counter.builder("cache.operations")
.tag("cache", cacheName)
.tag("result", hit ? "hit" : "miss")
.register(registry)
.increment();
}
public void recordBusinessMetric(String metricName, double value, Map<String, String> tags) {
DistributionSummary.Builder builder = DistributionSummary.builder(metricName);
tags.forEach(builder::tag);
builder.register(registry).record(value);
}
}Security Configuration Examples
Complete Security Setup
@Configuration
@EnableWebSecurity
public class ActuatorSecurityConfiguration {
@Bean
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
// Public health check (for load balancers)
.requestMatchers(EndpointRequest.to(HealthEndpoint.class)).permitAll()
// Info endpoint for authenticated users
.requestMatchers(EndpointRequest.to(InfoEndpoint.class)).authenticated()
// Read-only metrics for monitoring role
.requestMatchers(HttpMethod.GET, "/actuator/metrics/**")
.hasAnyRole("MONITOR", "ADMIN")
// Prometheus endpoint for monitoring tools
.requestMatchers(EndpointRequest.to("prometheus"))
.hasRole("MONITOR")
// Write operations only for admin
.requestMatchers(HttpMethod.POST, "/actuator/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/actuator/**").hasRole("ADMIN")
// Everything else requires admin
.anyRequest().hasRole("ADMIN")
)
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
public UserDetailsService actuatorUsers() {
UserDetails monitor = User.builder()
.username("monitor")
.password("{noop}monitor-password")
.roles("MONITOR")
.build();
UserDetails admin = User.builder()
.username("admin")
.password("{noop}admin-password")
.roles("ADMIN", "MONITOR")
.build();
return new InMemoryUserDetailsManager(monitor, admin);
}
}IP-Based Access Control
@Configuration
public class IpBasedActuatorSecurity {
@Bean
public SecurityFilterChain actuatorSecurity(HttpSecurity http) throws Exception {
return http
.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth
.requestMatchers(request ->
isFromAllowedIp(request.getRemoteAddr())
).permitAll()
.anyRequest().denyAll()
)
.build();
}
private boolean isFromAllowedIp(String remoteAddr) {
// Allow localhost and specific IPs
return remoteAddr.equals("127.0.0.1") ||
remoteAddr.equals("0:0:0:0:0:0:0:1") ||
remoteAddr.startsWith("10.0.0.");
}
}Testing Examples
Health Indicator Tests
@SpringBootTest
class DatabaseHealthIndicatorTest {
@Autowired
private DatabaseHealthIndicator healthIndicator;
@MockBean
private DataSource dataSource;
@Test
void shouldReturnUpWhenDatabaseIsHealthy() throws Exception {
Connection connection = mock(Connection.class);
when(dataSource.getConnection()).thenReturn(connection);
when(connection.isValid(1000)).thenReturn(true);
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
when(connection.getMetaData()).thenReturn(metaData);
when(metaData.getDatabaseProductName()).thenReturn("PostgreSQL");
Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.UP);
assertThat(health.getDetails()).containsKey("database");
}
@Test
void shouldReturnDownWhenDatabaseConnectionFails() throws Exception {
when(dataSource.getConnection()).thenThrow(new SQLException("Connection failed"));
Health health = healthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails()).containsKey("error");
}
}Endpoint Tests
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class ActuatorEndpointIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void healthEndpointShouldBeAccessible() throws Exception {
mockMvc.perform(get("/actuator/health"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("UP"));
}
@Test
void metricsEndpointShouldListAvailableMetrics() throws Exception {
mockMvc.perform(get("/actuator/metrics"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.names").isArray())
.andExpect(jsonPath("$.names[*]", hasItem("jvm.memory.used")));
}
@Test
void customEndpointShouldWork() throws Exception {
mockMvc.perform(get("/actuator/features"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@Test
@WithMockUser(roles = "ADMIN")
void securedEndpointShouldRequireAuthentication() throws Exception {
mockMvc.perform(post("/actuator/features/test")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"enabled\":true}"))
.andExpect(status().isOk());
}
}Kubernetes Integration Example
Deployment with Probes
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
replicas: 3
selector:
matchLabels:
app: order-service
template:
metadata:
labels:
app: order-service
spec:
containers:
- name: order-service
image: order-service:1.0.0
ports:
- containerPort: 8080
name: http
- containerPort: 8081
name: management
env:
- name: MANAGEMENT_SERVER_PORT
value: "8081"
- name: MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE
value: "health,info,prometheus"
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: management
initialDelaySeconds: 60
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: management
initialDelaySeconds: 30
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
---
apiVersion: v1
kind: Service
metadata:
name: order-service
spec:
selector:
app: order-service
ports:
- name: http
port: 8080
targetPort: http
- name: management
port: 8081
targetPort: managementServiceMonitor for Prometheus Operator
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: order-service-metrics
labels:
app: order-service
spec:
selector:
matchLabels:
app: order-service
endpoints:
- port: management
path: /actuator/prometheus
interval: 30s
scrapeTimeout: 10sHTTP Exchanges
You can enable recording of HTTP exchanges by providing a bean of type HttpExchangeRepository in your application's configuration. For convenience, Spring Boot offers InMemoryHttpExchangeRepository, which, by default, stores the last 100 request-response exchanges. InMemoryHttpExchangeRepository is limited compared to tracing solutions, and we recommend using it only for development environments. For production environments, we recommend using a production-ready tracing or observability solution, such as Zipkin or OpenTelemetry. Alternatively, you can create your own HttpExchangeRepository.
You can use the httpexchanges endpoint to obtain information about the request-response exchanges that are stored in the HttpExchangeRepository.
Basic Configuration
In-Memory Repository (Development)
@Configuration
public class HttpExchangesConfiguration {
@Bean
public InMemoryHttpExchangeRepository httpExchangeRepository() {
return new InMemoryHttpExchangeRepository();
}
}Custom Repository Size
@Configuration
public class HttpExchangesConfiguration {
@Bean
public InMemoryHttpExchangeRepository httpExchangeRepository() {
return new InMemoryHttpExchangeRepository(1000); // Store last 1000 exchanges
}
}Custom HTTP Exchange Recording
To customize the items that are included in each recorded exchange, use the management.httpexchanges.recording.include configuration property:
management:
httpexchanges:
recording:
include:
- request-headers
- response-headers
- cookie-headers
- authorization-header
- principal
- remote-address
- session-id
- time-takenAvailable options:
request-headers: Include request headersresponse-headers: Include response headerscookie-headers: Include cookie headersauthorization-header: Include authorization headerprincipal: Include principal informationremote-address: Include remote addresssession-id: Include session IDtime-taken: Include request processing time
Custom HTTP Exchange Repository
Database-backed Repository
@Entity
@Table(name = "http_exchanges")
public class HttpExchangeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "timestamp")
private Instant timestamp;
@Column(name = "method")
private String method;
@Column(name = "uri", length = 2000)
private String uri;
@Column(name = "status")
private Integer status;
@Column(name = "time_taken")
private Long timeTaken;
@Column(name = "principal")
private String principal;
@Column(name = "remote_address")
private String remoteAddress;
@Column(name = "session_id")
private String sessionId;
@Lob
@Column(name = "request_headers")
private String requestHeaders;
@Lob
@Column(name = "response_headers")
private String responseHeaders;
// Constructors, getters, setters
}
@Repository
public interface HttpExchangeEntityRepository extends JpaRepository<HttpExchangeEntity, Long> {
List<HttpExchangeEntity> findTop100ByOrderByTimestampDesc();
@Modifying
@Query("DELETE FROM HttpExchangeEntity h WHERE h.timestamp < :cutoff")
void deleteOlderThan(@Param("cutoff") Instant cutoff);
}
@Component
public class DatabaseHttpExchangeRepository implements HttpExchangeRepository {
private final HttpExchangeEntityRepository repository;
private final ObjectMapper objectMapper;
public DatabaseHttpExchangeRepository(HttpExchangeEntityRepository repository) {
this.repository = repository;
this.objectMapper = new ObjectMapper();
}
@Override
public List<HttpExchange> findAll() {
return repository.findTop100ByOrderByTimestampDesc()
.stream()
.map(this::toHttpExchange)
.collect(Collectors.toList());
}
@Override
public void add(HttpExchange httpExchange) {
HttpExchangeEntity entity = toEntity(httpExchange);
repository.save(entity);
}
private HttpExchangeEntity toEntity(HttpExchange exchange) {
HttpExchangeEntity entity = new HttpExchangeEntity();
entity.setTimestamp(exchange.getTimestamp());
HttpExchange.Request request = exchange.getRequest();
entity.setMethod(request.getMethod());
entity.setUri(request.getUri().toString());
entity.setPrincipal(exchange.getPrincipal() != null ?
exchange.getPrincipal().getName() : null);
entity.setRemoteAddress(request.getRemoteAddress());
if (exchange.getResponse() != null) {
entity.setStatus(exchange.getResponse().getStatus());
}
entity.setTimeTaken(exchange.getTimeTaken() != null ?
exchange.getTimeTaken().toMillis() : null);
try {
entity.setRequestHeaders(objectMapper.writeValueAsString(request.getHeaders()));
if (exchange.getResponse() != null) {
entity.setResponseHeaders(objectMapper.writeValueAsString(
exchange.getResponse().getHeaders()));
}
} catch (Exception e) {
// Handle serialization error
}
return entity;
}
private HttpExchange toHttpExchange(HttpExchangeEntity entity) {
// Implement conversion from entity to HttpExchange
// This is complex due to HttpExchange being immutable
// Consider using a builder pattern or reflection
return null; // Simplified for brevity
}
@Scheduled(fixedRate = 3600000) // Clean up every hour
public void cleanup() {
Instant cutoff = Instant.now().minus(Duration.ofDays(7));
repository.deleteOlderThan(cutoff);
}
}Filtered HTTP Exchange Repository
@Component
public class FilteredHttpExchangeRepository implements HttpExchangeRepository {
private final HttpExchangeRepository delegate;
private final Set<String> excludePaths;
private final Set<String> excludeUserAgents;
public FilteredHttpExchangeRepository(HttpExchangeRepository delegate) {
this.delegate = delegate;
this.excludePaths = Set.of("/actuator/health", "/actuator/metrics", "/favicon.ico");
this.excludeUserAgents = Set.of("kube-probe", "ELB-HealthChecker");
}
@Override
public List<HttpExchange> findAll() {
return delegate.findAll();
}
@Override
public void add(HttpExchange httpExchange) {
if (shouldRecord(httpExchange)) {
delegate.add(httpExchange);
}
}
private boolean shouldRecord(HttpExchange exchange) {
String path = exchange.getRequest().getUri().getPath();
// Skip health check and monitoring endpoints
if (excludePaths.contains(path)) {
return false;
}
// Skip requests from monitoring tools
String userAgent = exchange.getRequest().getHeaders().getFirst("User-Agent");
if (userAgent != null && excludeUserAgents.stream().anyMatch(userAgent::contains)) {
return false;
}
// Skip successful static resource requests
if (path.startsWith("/static/") || path.startsWith("/css/") || path.startsWith("/js/")) {
return exchange.getResponse() == null || exchange.getResponse().getStatus() >= 400;
}
return true;
}
}Async HTTP Exchange Recording
Async Repository Wrapper
@Component
public class AsyncHttpExchangeRepository implements HttpExchangeRepository {
private final HttpExchangeRepository delegate;
private final TaskExecutor taskExecutor;
public AsyncHttpExchangeRepository(HttpExchangeRepository delegate,
@Qualifier("httpExchangeTaskExecutor") TaskExecutor taskExecutor) {
this.delegate = delegate;
this.taskExecutor = taskExecutor;
}
@Override
public List<HttpExchange> findAll() {
return delegate.findAll();
}
@Override
public void add(HttpExchange httpExchange) {
taskExecutor.execute(() -> {
try {
delegate.add(httpExchange);
} catch (Exception e) {
// Log error but don't let it affect the main request
log.error("Failed to record HTTP exchange", e);
}
});
}
}
@Configuration
public class HttpExchangeTaskExecutorConfiguration {
@Bean("httpExchangeTaskExecutor")
public TaskExecutor httpExchangeTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(1000);
executor.setThreadNamePrefix("http-exchange-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
executor.initialize();
return executor;
}
}HTTP Exchanges Endpoint
Accessing HTTP Exchanges
GET /actuator/httpexchangesResponse format:
{
"exchanges": [
{
"timestamp": "2023-12-01T10:30:00.123Z",
"request": {
"method": "GET",
"uri": "http://localhost:8080/api/users/123",
"headers": {
"accept": ["application/json"],
"user-agent": ["Mozilla/5.0..."]
},
"remoteAddress": "192.168.1.100"
},
"response": {
"status": 200,
"headers": {
"content-type": ["application/json"],
"content-length": ["256"]
}
},
"principal": {
"name": "john.doe"
},
"session": {
"id": "JSESSIONID123"
},
"timeTaken": "PT0.025S"
}
]
}Securing the Endpoint
@Configuration
public class HttpExchangesSecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain httpExchangesSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.to("httpexchanges"))
.authorizeHttpRequests(requests ->
requests.anyRequest().hasRole("ADMIN"))
.httpBasic(withDefaults())
.build();
}
}Custom HTTP Exchange Information
Including Custom Data
@Component
public class CustomHttpExchangeRepository implements HttpExchangeRepository {
private final InMemoryHttpExchangeRepository delegate;
public CustomHttpExchangeRepository() {
this.delegate = new InMemoryHttpExchangeRepository();
}
@Override
public List<HttpExchange> findAll() {
return delegate.findAll();
}
@Override
public void add(HttpExchange httpExchange) {
HttpExchange enrichedExchange = enrichExchange(httpExchange);
delegate.add(enrichedExchange);
}
private HttpExchange enrichExchange(HttpExchange original) {
// Add custom information to the exchange
// Note: HttpExchange is immutable, so we need to create a wrapper
// or use reflection to modify internal state
// For demonstration, we'll just add it normally
// In practice, you might need to create a custom implementation
return original;
}
}
@Component
public class HttpExchangeEnricher {
public void enrich(HttpServletRequest request, HttpServletResponse response) {
// Add custom attributes that can be picked up by the repository
request.setAttribute("custom.trace.id", getTraceId());
request.setAttribute("custom.user.role", getUserRole());
request.setAttribute("custom.api.version", getApiVersion(request));
}
private String getTraceId() {
// Get from tracing context
return "trace-123";
}
private String getUserRole() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getAuthorities().toString() : "anonymous";
}
private String getApiVersion(HttpServletRequest request) {
return request.getHeader("API-Version");
}
}Performance Considerations
Configuration for Production
management:
httpexchanges:
recording:
include:
- time-taken
- principal
- remote-address
# Exclude detailed headers to reduce memory usage
exclude:
- request-headers
- response-headers
endpoint:
httpexchanges:
enabled: false # Disable in production for securityCustom Sampling
@Component
public class SamplingHttpExchangeRepository implements HttpExchangeRepository {
private final HttpExchangeRepository delegate;
private final Random random = new Random();
private final double samplingRate;
public SamplingHttpExchangeRepository(HttpExchangeRepository delegate,
@Value("${app.http-exchanges.sampling-rate:0.1}") double samplingRate) {
this.delegate = delegate;
this.samplingRate = samplingRate;
}
@Override
public List<HttpExchange> findAll() {
return delegate.findAll();
}
@Override
public void add(HttpExchange httpExchange) {
if (random.nextDouble() < samplingRate) {
delegate.add(httpExchange);
}
}
}Best Practices
1. Production Use: Disable HTTP exchanges endpoint in production or secure it properly 2. Memory Management: Use limited-size repositories to prevent memory leaks 3. Sensitive Data: Be careful not to log sensitive information in headers 4. Performance: Consider async recording for high-throughput applications 5. Sampling: Use sampling in production to reduce overhead 6. Retention: Implement cleanup policies for stored exchanges 7. Security: Ensure recorded data doesn't contain credentials or tokens
Production Configuration Example
management:
endpoint:
httpexchanges:
enabled: false # Disabled in production
httpexchanges:
recording:
include:
- time-taken
- principal
- remote-address
exclude:
- authorization-header
- cookie-headers
- request-headers
- response-headers
logging:
level:
org.springframework.boot.actuate.web.exchanges: WARNJMX with Spring Boot Actuator
Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, this feature is not enabled. You can turn it on by setting the spring.jmx.enabled configuration property to true. Spring Boot exposes the most suitable MBeanServer as a bean with an ID of mbeanServer. Any of your beans that are annotated with Spring JMX annotations (@ManagedResource, @ManagedAttribute, or @ManagedOperation) are exposed to it.
If your platform provides a standard MBeanServer, Spring Boot uses that and defaults to the VM MBeanServer, if necessary. If all that fails, a new MBeanServer is created.
NOTE
>
spring.jmx.enabled affects only the management beans provided by Spring. Enabling management beans provided by other libraries (for example Log4j2 or Quartz) is independent.Basic JMX Configuration
Enabling JMX
spring:
jmx:
enabled: true
default-domain: com.example.myapp
management:
endpoints:
jmx:
exposure:
include: "*"
endpoint:
jmx:
enabled: trueCustom MBean Server Configuration
@Configuration
public class JmxConfiguration {
@Bean
@Primary
public MBeanServer mbeanServer() {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
return server;
}
@Bean
public JmxMetricsExporter jmxMetricsExporter(MeterRegistry meterRegistry) {
return new JmxMetricsExporter(meterRegistry);
}
}Creating Custom MBeans
Using @ManagedResource Annotation
@Component
@ManagedResource(
objectName = "com.example:type=ApplicationMetrics,name=UserService",
description = "User Service Management Bean"
)
public class UserServiceMBean {
private final UserService userService;
private long totalUsers = 0;
private long activeUsers = 0;
public UserServiceMBean(UserService userService) {
this.userService = userService;
}
@ManagedAttribute(description = "Total number of users")
public long getTotalUsers() {
return userService.getTotalUserCount();
}
@ManagedAttribute(description = "Number of active users")
public long getActiveUsers() {
return userService.getActiveUserCount();
}
@ManagedAttribute(description = "Cache hit ratio")
public double getCacheHitRatio() {
return userService.getCacheHitRatio();
}
@ManagedOperation(description = "Clear user cache")
public void clearCache() {
userService.clearCache();
}
@ManagedOperation(description = "Refresh user statistics")
public String refreshStatistics() {
userService.refreshStatistics();
return "Statistics refreshed at " + Instant.now();
}
@ManagedOperation(description = "Get user by ID")
@ManagedOperationParameters({
@ManagedOperationParameter(name = "userId", description = "User ID")
})
public String getUserInfo(Long userId) {
User user = userService.findById(userId);
return user != null ? user.toString() : "User not found";
}
}Implementing MBean Interface
public interface ApplicationConfigMBean {
String getEnvironment();
void setLogLevel(String loggerName, String level);
boolean isMaintenanceMode();
void setMaintenanceMode(boolean maintenanceMode);
void reloadConfiguration();
Map<String, String> getSystemProperties();
}
@Component
public class ApplicationConfig implements ApplicationConfigMBean {
private final Environment environment;
private final LoggingSystem loggingSystem;
private boolean maintenanceMode = false;
public ApplicationConfig(Environment environment, LoggingSystem loggingSystem) {
this.environment = environment;
this.loggingSystem = loggingSystem;
}
@Override
public String getEnvironment() {
return String.join(",", environment.getActiveProfiles());
}
@Override
public void setLogLevel(String loggerName, String level) {
LogLevel logLevel = level != null ? LogLevel.valueOf(level.toUpperCase()) : null;
loggingSystem.setLogLevel(loggerName, logLevel);
}
@Override
public boolean isMaintenanceMode() {
return maintenanceMode;
}
@Override
public void setMaintenanceMode(boolean maintenanceMode) {
this.maintenanceMode = maintenanceMode;
// Publish event or notify other components
}
@Override
public void reloadConfiguration() {
// Implement configuration reload logic
// This could refresh @ConfigurationProperties beans
}
@Override
public Map<String, String> getSystemProperties() {
return System.getProperties().entrySet().stream()
.collect(Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> String.valueOf(e.getValue())
));
}
@PostConstruct
public void registerMBean() {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("com.example:type=ApplicationConfig");
server.registerMBean(this, objectName);
} catch (Exception e) {
throw new RuntimeException("Failed to register MBean", e);
}
}
}Application Metrics via JMX
Custom Metrics MBean
@Component
@ManagedResource(
objectName = "com.example:type=Performance,name=ApplicationMetrics",
description = "Application Performance Metrics"
)
public class ApplicationMetricsMBean {
private final MeterRegistry meterRegistry;
private final Counter requestCounter;
private final Timer responseTimer;
private final Gauge activeConnections;
public ApplicationMetricsMBean(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.requestCounter = Counter.builder("application.requests.total")
.description("Total number of requests")
.register(meterRegistry);
this.responseTimer = Timer.builder("application.response.time")
.description("Response time")
.register(meterRegistry);
this.activeConnections = Gauge.builder("application.connections.active")
.description("Active connections")
.register(meterRegistry, this, ApplicationMetricsMBean::getActiveConnectionsCount);
}
@ManagedAttribute(description = "Total requests processed")
public long getTotalRequests() {
return (long) requestCounter.count();
}
@ManagedAttribute(description = "Average response time in milliseconds")
public double getAverageResponseTime() {
return responseTimer.mean(TimeUnit.MILLISECONDS);
}
@ManagedAttribute(description = "95th percentile response time")
public double getResponse95thPercentile() {
return responseTimer.percentile(0.95, TimeUnit.MILLISECONDS);
}
@ManagedAttribute(description = "Current active connections")
public long getActiveConnections() {
return getActiveConnectionsCount();
}
@ManagedAttribute(description = "JVM memory usage percentage")
public double getMemoryUsagePercentage() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
return (double) heapUsage.getUsed() / heapUsage.getMax() * 100;
}
@ManagedOperation(description = "Reset request counter")
public void resetRequestCounter() {
// Note: Micrometer counters cannot be reset, this would require custom implementation
// or using a different metric type
}
private long getActiveConnectionsCount() {
// Implementation to get actual active connections
return 42; // Placeholder
}
}Database Connection Pool MBean
@Component
@ManagedResource(
objectName = "com.example:type=Database,name=ConnectionPool",
description = "Database Connection Pool Metrics"
)
public class DatabaseConnectionPoolMBean {
private final DataSource dataSource;
public DatabaseConnectionPoolMBean(DataSource dataSource) {
this.dataSource = dataSource;
}
@ManagedAttribute(description = "Active connections")
public int getActiveConnections() {
if (dataSource instanceof HikariDataSource) {
return ((HikariDataSource) dataSource).getHikariPoolMXBean().getActiveConnections();
}
return -1; // Not supported
}
@ManagedAttribute(description = "Idle connections")
public int getIdleConnections() {
if (dataSource instanceof HikariDataSource) {
return ((HikariDataSource) dataSource).getHikariPoolMXBean().getIdleConnections();
}
return -1; // Not supported
}
@ManagedAttribute(description = "Total connections")
public int getTotalConnections() {
if (dataSource instanceof HikariDataSource) {
return ((HikariDataSource) dataSource).getHikariPoolMXBean().getTotalConnections();
}
return -1; // Not supported
}
@ManagedAttribute(description = "Threads awaiting connection")
public int getThreadsAwaitingConnection() {
if (dataSource instanceof HikariDataSource) {
return ((HikariDataSource) dataSource).getHikariPoolMXBean().getThreadsAwaitingConnection();
}
return -1; // Not supported
}
@ManagedOperation(description = "Suspend connection pool")
public void suspendPool() {
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).getHikariPoolMXBean().suspendPool();
}
}
@ManagedOperation(description = "Resume connection pool")
public void resumePool() {
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).getHikariPoolMXBean().resumePool();
}
}
}Security and JMX
Securing JMX Access
spring:
jmx:
enabled: true
management:
endpoints:
jmx:
exposure:
include: "health,info,metrics"
exclude: "env,configprops" # Exclude sensitive endpoints
# JMX-specific security
com.sun.management.jmxremote.port: 9999
com.sun.management.jmxremote.authenticate: true
com.sun.management.jmxremote.ssl: false
com.sun.management.jmxremote.access.file: /path/to/jmxremote.access
com.sun.management.jmxremote.password.file: /path/to/jmxremote.passwordCustom JMX Security
@Configuration
public class JmxSecurityConfiguration {
@Bean
public JMXConnectorServer jmxConnectorServer() throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:9999");
Map<String, Object> environment = new HashMap<>();
environment.put(JMXConnectorServer.AUTHENTICATOR, new CustomJMXAuthenticator());
JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(
url, environment, ManagementFactory.getPlatformMBeanServer());
server.start();
return server;
}
private static class CustomJMXAuthenticator implements JMXAuthenticator {
@Override
public Subject authenticate(Object credentials) {
if (!(credentials instanceof String[])) {
throw new SecurityException("Credentials must be String[]");
}
String[] creds = (String[]) credentials;
if (creds.length != 2) {
throw new SecurityException("Credentials must contain username and password");
}
String username = creds[0];
String password = creds[1];
// Implement your authentication logic
if ("admin".equals(username) && "password".equals(password)) {
return new Subject();
}
throw new SecurityException("Authentication failed");
}
}
}Monitoring and Alerting with JMX
Health Check MBean
@Component
@ManagedResource(
objectName = "com.example:type=Health,name=ApplicationHealth",
description = "Application Health Monitoring"
)
public class ApplicationHealthMBean {
private final HealthEndpoint healthEndpoint;
private final List<String> healthIssues = new ArrayList<>();
public ApplicationHealthMBean(HealthEndpoint healthEndpoint) {
this.healthEndpoint = healthEndpoint;
}
@ManagedAttribute(description = "Overall application health status")
public String getHealthStatus() {
HealthComponent health = healthEndpoint.health();
return health.getStatus().getCode();
}
@ManagedAttribute(description = "Detailed health information")
public String getHealthDetails() {
HealthComponent health = healthEndpoint.health();
return health.toString();
}
@ManagedAttribute(description = "Database health status")
public String getDatabaseHealth() {
HealthComponent health = healthEndpoint.healthForPath("db");
return health != null ? health.getStatus().getCode() : "UNKNOWN";
}
@ManagedAttribute(description = "Current health issues")
public String[] getHealthIssues() {
return healthIssues.toArray(new String[0]);
}
@ManagedOperation(description = "Refresh health status")
public void refreshHealth() {
HealthComponent health = healthEndpoint.health();
healthIssues.clear();
if (health instanceof CompositeHealthComponent) {
CompositeHealthComponent composite = (CompositeHealthComponent) health;
composite.getComponents().forEach((name, component) -> {
if (!Status.UP.equals(component.getStatus())) {
healthIssues.add(name + ": " + component.getStatus().getCode());
}
});
}
}
@PostConstruct
public void init() {
refreshHealth();
}
}Notification MBean
@Component
@ManagedResource(
objectName = "com.example:type=Notifications,name=AlertManager",
description = "Application Alert Management"
)
public class AlertManagerMBean extends NotificationBroadcasterSupport {
private final AtomicLong sequenceNumber = new AtomicLong(0);
private boolean alertsEnabled = true;
@ManagedAttribute(description = "Are alerts enabled")
public boolean isAlertsEnabled() {
return alertsEnabled;
}
@ManagedAttribute(description = "Enable or disable alerts")
public void setAlertsEnabled(boolean alertsEnabled) {
this.alertsEnabled = alertsEnabled;
}
@ManagedOperation(description = "Send test alert")
public void sendTestAlert() {
sendAlert("TEST", "Test alert from JMX", "INFO");
}
public void sendAlert(String type, String message, String severity) {
if (!alertsEnabled) {
return;
}
Notification notification = new Notification(
type,
this,
sequenceNumber.incrementAndGet(),
System.currentTimeMillis(),
message
);
notification.setUserData(Map.of(
"severity", severity,
"timestamp", Instant.now().toString()
));
sendNotification(notification);
}
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return new MBeanNotificationInfo[]{
new MBeanNotificationInfo(
new String[]{"HEALTH", "PERFORMANCE", "SECURITY", "TEST"},
Notification.class.getName(),
"Application alerts and notifications"
)
};
}
}Best Practices
1. Naming Convention: Use consistent ObjectName patterns 2. Security: Always secure JMX access in production 3. Performance: Be mindful of expensive operations in MBean methods 4. Documentation: Provide clear descriptions for attributes and operations 5. Error Handling: Handle exceptions gracefully in MBean operations 6. Resource Management: Properly manage resources in MBean operations 7. Monitoring: Monitor JMX itself for availability and performance
Production JMX Configuration
# Production JMX configuration
spring:
jmx:
enabled: true
default-domain: "com.mycompany.myapp"
management:
endpoints:
jmx:
exposure:
include: "health,info,metrics"
exclude: "env,configprops,beans"
endpoint:
jmx:
enabled: true
# JVM JMX settings (set as JVM arguments)
# -Dcom.sun.management.jmxremote=true
# -Dcom.sun.management.jmxremote.port=9999
# -Dcom.sun.management.jmxremote.authenticate=true
# -Dcom.sun.management.jmxremote.ssl=true
# -Dcom.sun.management.jmxremote.access.file=/etc/jmx/jmxremote.access
# -Dcom.sun.management.jmxremote.password.file=/etc/jmx/jmxremote.passwordJMX Client Example
public class JmxClient {
public static void main(String[] args) throws Exception {
String url = "service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi";
JMXServiceURL serviceURL = new JMXServiceURL(url);
Map<String, Object> environment = new HashMap<>();
environment.put(JMXConnector.CREDENTIALS, new String[]{"admin", "password"});
try (JMXConnector connector = JMXConnectorFactory.connect(serviceURL, environment)) {
MBeanServerConnection connection = connector.getMBeanServerConnection();
// Get application health
ObjectName healthName = new ObjectName("com.example:type=Health,name=ApplicationHealth");
String healthStatus = (String) connection.getAttribute(healthName, "HealthStatus");
System.out.println("Health Status: " + healthStatus);
// Invoke operation
connection.invoke(healthName, "refreshHealth", null, null);
// Listen for notifications
ObjectName alertName = new ObjectName("com.example:type=Notifications,name=AlertManager");
connection.addNotificationListener(alertName,
(notification, handback) -> {
System.out.println("Alert: " + notification.getMessage());
}, null, null);
}
}
}Loggers Endpoint
Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger's configuration, which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. These levels can be one of:
TRACEDEBUGINFOWARNERRORFATALOFFnull
null indicates that there is no explicit configuration.
Viewing Logger Configuration
View All Loggers
To view the configuration of all loggers:
GET /actuator/loggersResponse example:
{
"levels": ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"],
"loggers": {
"ROOT": {
"configuredLevel": "INFO",
"effectiveLevel": "INFO"
},
"com.example": {
"configuredLevel": null,
"effectiveLevel": "INFO"
},
"com.example.MyClass": {
"configuredLevel": "DEBUG",
"effectiveLevel": "DEBUG"
}
}
}View Specific Logger
To view the configuration of a specific logger:
GET /actuator/loggers/com.example.MyClassResponse example:
{
"configuredLevel": "DEBUG",
"effectiveLevel": "DEBUG"
}Configuring a Logger
To configure a given logger, POST a partial entity to the resource's URI, as the following example shows:
POST /actuator/loggers/com.example.MyClass
Content-Type: application/json
{
"configuredLevel": "DEBUG"
}TIP
>
To "reset" the specific level of the logger (and use the default configuration instead), you can pass a value ofnullas theconfiguredLevel.
Reset Logger Level
To reset a logger to its default level:
POST /actuator/loggers/com.example.MyClass
Content-Type: application/json
{
"configuredLevel": null
}Configuration Examples
Enable Debug Logging for Specific Package
curl -X POST http://localhost:8080/actuator/loggers/com.example.service \
-H "Content-Type: application/json" \
-d '{"configuredLevel": "DEBUG"}'Enable Trace Logging for Spring Security
curl -X POST http://localhost:8080/actuator/loggers/org.springframework.security \
-H "Content-Type: application/json" \
-d '{"configuredLevel": "TRACE"}'Set Root Logger Level
curl -X POST http://localhost:8080/actuator/loggers/ROOT \
-H "Content-Type: application/json" \
-d '{"configuredLevel": "WARN"}'Programmatic Logger Management
You can also manage loggers programmatically in your application:
@RestController
public class LoggerController {
private final LoggingSystem loggingSystem;
public LoggerController(LoggingSystem loggingSystem) {
this.loggingSystem = loggingSystem;
}
@PostMapping("/admin/logger/{name}")
public void setLogLevel(@PathVariable String name, @RequestBody LogLevelRequest request) {
LogLevel level = request.getLevel() != null ?
LogLevel.valueOf(request.getLevel().toUpperCase()) : null;
loggingSystem.setLogLevel(name, level);
}
public static class LogLevelRequest {
private String level;
public String getLevel() { return level; }
public void setLevel(String level) { this.level = level; }
}
}Conditional Logging
Environment-based Configuration
logging:
level:
com.example: ${LOGGING_LEVEL_EXAMPLE:INFO}
org.springframework.web: ${LOGGING_LEVEL_WEB:WARN}
org.hibernate.SQL: ${LOGGING_LEVEL_SQL:WARN}
org.hibernate.type.descriptor.sql: ${LOGGING_LEVEL_SQL_PARAMS:WARN}
---
spring:
config:
activate:
on-profile: development
logging:
level:
com.example: DEBUG
org.hibernate.SQL: DEBUG
org.hibernate.type.descriptor.sql: TRACE
---
spring:
config:
activate:
on-profile: production
logging:
level:
root: WARN
com.example: INFOFeature Toggle Logging
@Component
public class FeatureLoggingController {
private final LoggingSystem loggingSystem;
private final Environment environment;
public FeatureLoggingController(LoggingSystem loggingSystem, Environment environment) {
this.loggingSystem = loggingSystem;
this.environment = environment;
}
@EventListener
public void handleFeatureToggleChange(FeatureToggleEvent event) {
if ("debug-logging".equals(event.getFeatureName())) {
if (event.isEnabled()) {
enableDebugLogging();
} else {
disableDebugLogging();
}
}
}
private void enableDebugLogging() {
loggingSystem.setLogLevel("com.example.service", LogLevel.DEBUG);
loggingSystem.setLogLevel("com.example.repository", LogLevel.DEBUG);
}
private void disableDebugLogging() {
loggingSystem.setLogLevel("com.example.service", null);
loggingSystem.setLogLevel("com.example.repository", null);
}
}Security Considerations
Securing the Loggers Endpoint
@Configuration
public class LoggersSecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain loggersSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.to("loggers"))
.authorizeHttpRequests(requests ->
requests.anyRequest().hasRole("ADMIN"))
.httpBasic(withDefaults())
.build();
}
}Read-only Access
To provide read-only access to the loggers endpoint:
management:
endpoint:
loggers:
access: read-onlyOr configure programmatically:
@Configuration
public class LoggersAccessConfig {
@Bean
@Order(1)
public SecurityFilterChain loggersSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.to("loggers"))
.authorizeHttpRequests(requests ->
requests
.requestMatchers(HttpMethod.GET).hasRole("LOGGER_READER")
.requestMatchers(HttpMethod.POST).hasRole("LOGGER_ADMIN")
.anyRequest().denyAll())
.httpBasic(withDefaults())
.build();
}
}OpenTelemetry Integration
By default, logging via OpenTelemetry is not configured. You have to provide the location of the OpenTelemetry logs endpoint to configure it:
management:
otlp:
logging:
endpoint: "https://otlp.example.com:4318/v1/logs"NOTE
>
The OpenTelemetry Logback appender and Log4j appender are not part of Spring Boot. For more details, see the OpenTelemetry Logback appender or the OpenTelemetry Log4j2 appender in the OpenTelemetry Java instrumentation GitHub repository.
TIP
>
You have to configure the appender in yourlogback-spring.xmlorlog4j2-spring.xmlconfiguration to get OpenTelemetry logging working.
The OpenTelemetryAppender for both Logback and Log4j requires access to an OpenTelemetry instance to function properly. This instance must be set programmatically during application startup:
@Component
public class OpenTelemetryAppenderInitializer {
public OpenTelemetryAppenderInitializer(OpenTelemetry openTelemetry) {
// Configure Logback appender
if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.getStatusManager().add(new OnConsoleStatusListener());
OpenTelemetryAppender appender = new OpenTelemetryAppender();
appender.setContext(context);
appender.setOpenTelemetry(openTelemetry);
appender.start();
ch.qos.logback.classic.Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.addAppender(appender);
}
}
}Best Practices
1. Monitor Performance: Changing log levels at runtime can impact application performance 2. Security: Always secure the loggers endpoint in production environments 3. Audit Changes: Log when log levels are changed and by whom 4. Temporary Changes: Consider making runtime log level changes temporary 5. Documentation: Document the purpose of different log levels in your application 6. Testing: Test your application with different log levels to ensure it performs well 7. Correlation IDs: Use correlation IDs to track requests across log entries
Audit Log Level Changes
@Component
public class LoggerAuditListener {
private static final Logger logger = LoggerFactory.getLogger(LoggerAuditListener.class);
@EventListener
public void handleLoggerConfigurationChange(LoggerConfigurationChangeEvent event) {
String username = getCurrentUsername();
logger.info("Logger level changed: logger={}, oldLevel={}, newLevel={}, user={}",
event.getLoggerName(),
event.getOldLevel(),
event.getNewLevel(),
username);
}
private String getCurrentUsername() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getName() : "system";
}
}Temporary Log Level Changes
@Component
public class TemporaryLogLevelManager {
private final LoggingSystem loggingSystem;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final Map<String, LogLevel> originalLevels = new ConcurrentHashMap<>();
public TemporaryLogLevelManager(LoggingSystem loggingSystem) {
this.loggingSystem = loggingSystem;
}
public void setTemporaryLogLevel(String loggerName, LogLevel level, Duration duration) {
// Store original level
LoggerConfiguration config = loggingSystem.getLoggerConfiguration(loggerName);
originalLevels.put(loggerName, config.getConfiguredLevel());
// Set new level
loggingSystem.setLogLevel(loggerName, level);
// Schedule reset
scheduler.schedule(() -> resetLogLevel(loggerName), duration.toMillis(), TimeUnit.MILLISECONDS);
}
private void resetLogLevel(String loggerName) {
LogLevel originalLevel = originalLevels.remove(loggerName);
loggingSystem.setLogLevel(loggerName, originalLevel);
}
}HTTP Monitoring and Management
If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the id of the endpoint with a prefix of /actuator as the URL path. For example, health is exposed as /actuator/health.
TIP
>
Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. If both Jersey and Spring MVC are available, Spring MVC is used.
NOTE
>
Jackson is a required dependency in order to get the correct JSON responses as documented in the API documentation.
Customizing the Management Endpoint Paths
Sometimes, it is useful to customize the prefix for the management endpoints. For example, your application might already use /actuator for another purpose. You can use the management.endpoints.web.base-path property to change the prefix for your management endpoint, as the following example shows:
management:
endpoints:
web:
base-path: "/manage"The preceding example changes the endpoint from /actuator/{id} to /manage/{id} (for example, /manage/info).
NOTE
>
Unless the management port has been configured to expose endpoints by using a different HTTP port,management.endpoints.web.base-pathis relative toserver.servlet.context-path(for servlet web applications) orspring.webflux.base-path(for reactive web applications). Ifmanagement.server.portis configured,management.endpoints.web.base-pathis relative tomanagement.server.base-path.
If you want to map endpoints to a different path, you can use the management.endpoints.web.path-mapping property.
The following example remaps /actuator/health to /healthcheck:
management:
endpoints:
web:
base-path: "/"
path-mapping:
health: "healthcheck"Customizing the Management Server Port
Exposing management endpoints by using the default HTTP port is a sensible choice for cloud-based deployments. If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port.
You can set the management.server.port property to change the HTTP port, as the following example shows:
management:
server:
port: 8081NOTE
>
On Cloud Foundry, by default, applications receive requests only on port 8080 for both HTTP and TCP routing. If you want to use a custom management port on Cloud Foundry, you need to explicitly set up the application's routes to forward traffic to the custom port.
Configuring Management-specific SSL
When configured to use a custom port, you can also configure the management server with its own SSL by using the various management.server.ssl.* properties. For example, doing so lets a management server be available over HTTP while the main application uses HTTPS, as the following property settings show:
server:
port: 8443
ssl:
enabled: true
key-store: "classpath:store.jks"
key-password: "secret"
management:
server:
port: 8080
ssl:
enabled: falseAlternatively, both the main server and the management server can use SSL but with different key stores, as follows:
server:
port: 8443
ssl:
enabled: true
key-store: "classpath:main.jks"
key-password: "secret"
management:
server:
port: 8080
ssl:
enabled: true
key-store: "classpath:management.jks"
key-password: "secret"Customizing the Management Server Address
You can customize the address on which the management endpoints are available by setting the management.server.address property. Doing so can be useful if you want to listen only on an internal or ops-facing network or to listen only for connections from localhost.
NOTE
>
You can listen on a different address only when the port differs from the main server port.
The following example does not allow remote management connections:
management:
server:
port: 8081
address: "127.0.0.1"Disabling HTTP Endpoints
If you do not want to expose endpoints over HTTP, you can set the management port to -1, as the following example shows:
management:
server:
port: -1You can also achieve this by using the management.endpoints.web.exposure.exclude property, as the following example shows:
management:
endpoints:
web:
exposure:
exclude: "*"Security Configuration for Management Endpoints
Basic Authentication
To secure management endpoints with basic authentication:
spring:
security:
user:
name: admin
password: secret
roles: ACTUATOR
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: when-authorizedCustom Security Configuration
For more granular control, create a custom security configuration:
@Configuration
public class ManagementSecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(requests ->
requests
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
.anyRequest().hasRole("ACTUATOR")
)
.httpBasic(withDefaults())
.build();
}
@Bean
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(requests ->
requests.anyRequest().authenticated())
.formLogin(withDefaults())
.build();
}
}Role-based Access Control
Different endpoints can require different roles:
@Configuration
public class ActuatorSecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(requests ->
requests
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
.requestMatchers(EndpointRequest.to("metrics", "prometheus")).hasRole("METRICS_READER")
.requestMatchers(EndpointRequest.to("env", "configprops")).hasRole("CONFIG_READER")
.requestMatchers(EndpointRequest.to("shutdown")).hasRole("ADMIN")
.anyRequest().hasRole("ACTUATOR")
)
.httpBasic(withDefaults())
.build();
}
}CORS Configuration
To enable Cross-Origin Resource Sharing (CORS) for management endpoints:
management:
endpoints:
web:
cors:
allowed-origins: "https://example.com"
allowed-methods: "GET,POST"
allowed-headers: "*"
allow-credentials: trueCustom Management Context Path
When using a separate management port, you can configure a custom context path:
management:
server:
port: 9090
base-path: "/admin"
endpoints:
web:
base-path: "/actuator"This configuration makes endpoints available at http://localhost:9090/admin/actuator/*.
Load Balancer Configuration
When running behind a load balancer, configure the health endpoint appropriately:
management:
endpoint:
health:
probes:
enabled: true
group:
liveness:
include: "livenessState"
readiness:
include: "readinessState,db"
endpoints:
web:
exposure:
include: "health,info,metrics"This allows the load balancer to check:
- Liveness:
GET /actuator/health/liveness - Readiness:
GET /actuator/health/readiness
Best Practices
1. Separate Management Port: Use a different port for management endpoints in production 2. Secure Endpoints: Always secure management endpoints in production environments 3. Limit Exposure: Only expose necessary endpoints (include specific endpoints rather than using *) 4. Monitor Access: Log and monitor access to management endpoints 5. Network Security: Use firewalls to restrict access to management ports 6. SSL/TLS: Use HTTPS for management endpoints in production 7. Health Checks: Configure appropriate health indicators for your infrastructure 8. Graceful Shutdown: Consider enabling graceful shutdown for production deployments
# Production-ready configuration example
server:
port: 8080
shutdown: graceful
management:
server:
port: 8081
address: "127.0.0.1" # Only local access
ssl:
enabled: true
key-store: "classpath:management.p12"
key-store-password: "${KEYSTORE_PASSWORD}"
endpoints:
web:
exposure:
include: "health,info,metrics,prometheus"
enabled-by-default: false
endpoint:
health:
enabled: true
show-details: when-authorized
probes:
enabled: true
info:
enabled: true
metrics:
enabled: true
prometheus:
enabled: true
spring:
lifecycle:
timeout-per-shutdown-phase: 30sProcess Monitoring
Spring Boot Actuator provides several features for monitoring the application process, including process information, thread dumps, and heap dumps.
Process Information
The info endpoint can provide process-specific information:
@Component
public class ProcessInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
builder.withDetail("process", Map.of(
"pid", ProcessHandle.current().pid(),
"uptime", Duration.ofMillis(runtime.getUptime()),
"start-time", Instant.ofEpochMilli(runtime.getStartTime()),
"jvm-name", runtime.getVmName(),
"jvm-version", runtime.getVmVersion()
));
}
}Thread Monitoring
Thread Dump Endpoint
Access thread dumps via:
GET /actuator/threaddumpCustom Thread Monitoring
@Component
@ManagedResource(objectName = "com.example:type=ThreadMonitor")
public class ThreadMonitorMBean {
@ManagedAttribute
public int getActiveThreadCount() {
return Thread.activeCount();
}
@ManagedAttribute
public long getTotalStartedThreadCount() {
return ManagementFactory.getThreadMXBean().getTotalStartedThreadCount();
}
@ManagedOperation
public String getThreadDump() {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos = threadBean.dumpAllThreads(true, true);
StringBuilder dump = new StringBuilder();
for (ThreadInfo threadInfo : threadInfos) {
dump.append(threadInfo.toString()).append("\n");
}
return dump.toString();
}
}Memory Monitoring
Heap Dump Endpoint
Access heap dumps via:
GET /actuator/heapdumpMemory Metrics
@Component
public class MemoryMetrics {
private final MeterRegistry meterRegistry;
public MemoryMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
Gauge.builder("memory.heap.usage")
.description("Heap memory usage percentage")
.register(meterRegistry, this, MemoryMetrics::getHeapUsagePercentage);
}
private double getHeapUsagePercentage() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
return (double) heapUsage.getUsed() / heapUsage.getMax() * 100;
}
}Process Health Monitoring
@Component
public class ProcessHealthIndicator implements HealthIndicator {
@Override
public Health health() {
try {
// Check process health
long pid = ProcessHandle.current().pid();
ProcessHandle process = ProcessHandle.of(pid).orElseThrow();
if (process.isAlive()) {
return Health.up()
.withDetail("pid", pid)
.withDetail("cpu-time", process.info().totalCpuDuration())
.withDetail("start-time", process.info().startInstant())
.build();
} else {
return Health.down()
.withDetail("reason", "Process not alive")
.build();
}
} catch (Exception ex) {
return Health.down(ex).build();
}
}
}Best Practices
1. Security: Secure heap dump and thread dump endpoints in production 2. Performance: Monitor the performance impact of process monitoring 3. Storage: Be aware that heap dumps can be very large files 4. Automation: Set up automated collection of thread dumps during incidents 5. Analysis: Use appropriate tools for analyzing heap and thread dumps
Related skills
How it compares
Use spring-boot-actuator for Spring Security authentication audit trails; use generic logging skills for non-security application logs.
FAQ
What does spring boot actuator do?
Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services. Use when setting up monito
When should I invoke spring boot actuator?
Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services. Use when setting up monito
What are key capabilities?
Deliver production-ready observability for Spring Boot services using Actuator endpoints, probes, and Micrometer integration.
Is Spring Boot Actuator safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.