crusy
crusy

Reputation: 1512

(Re) name Spring Boot HealthIndicator

I've got the following HealthIndicator:

@Component
public class FooBarHealthIndicator implements HealthIndicator {
  // ...

Which, on production, results in a JSON like:

status "DOWN"
  details
    fooBar
      status "DOWN"

But in my integration test the JSON looks like

status "DOWN"
  details
    com.acme.fooBar
      status "DOWN"

Note the package path.

So my question is: Who's responsible for naming HealthIndicators within the /health JSON? And (how) can I configure this?

PS: I already passed a name to @Component:

@Component("fooBar") // name clash!!
public class FooBarHealthIndicator implements HealthIndicator {
  // ...

which did the trick, but as FooBarHealthIndicator monitors a class FooBar, a bean of that name already is present. However, as it works in production without naming the HealthIndicator, there must be an additional way...

Upvotes: 4

Views: 2571

Answers (2)

Oliver
Oliver

Reputation: 4173

You can create the bean for your health indicator via a configuration class and set via name of your health indicator via the @Bean annotation, as shown below.

@Configuration
public class HealthIndicatorConfiguration {
    @Bean("MyServiceIndicator")
    public HealthIndicator healthIndicatorForMyService() {
        return new MyHealthIndicator();
    }
}

Upvotes: 0

Daniel
Daniel

Reputation: 4211

NOTE: This approach relies on exploitation of an internal implementation, which may change in the future. You have been warned.

The class responsible for naming the health indicator is called HealthIndicatorNameFactory and looks like this in Spring Boot 2.0.5.RELEASE:

public class HealthIndicatorNameFactory implements Function<String, String> {

    @Override
    public String apply(String name) {
        int index = name.toLowerCase(Locale.ENGLISH).indexOf("healthindicator");
        if (index > 0) {
            return name.substring(0, index);
        }
        return name;
    }

}

This means that if you name your @Component to (say) @Component("fooBarHealthIndicator") you should be able to get by without any bean name clashes. The name clash occurs when Spring is wiring up your beans, not by the Actuator itself.

Upvotes: 2

Related Questions