Using hostname in ConditionalOnProperty annotation

Scott Law :

We have an @Scheduled process that does a status check. But since it runs on an array of servers and provides the same information for each, we are getting 5 redundant messages.

To fix this, I found @ConditionalOnProperty which works great on my dev box with my host name hard-coded for the havingValue property and setting a statusHost property in the application-dev.yml. This seems like a great setup since it runs when they match and doesn't when they don't. Also has the advantage that if the yml does not have the property it doesn't run on any server for that environment.

So it looks something like this in the code:

@Component
@ConditionOnProperty(prefix="status.", value="host", havingValue="my-dev-box")
public class StatusChecker {}

And the yml:

status:
  host: my-dev-box

Unfortunately, when I went to clean things up and put in the right stuff, I realized that havingValue needs a constant and I am, of course, dynamically finding the hostname of the server.

@ConditionOnProperty(prefix="status.", value="host", havingValue=System.getProperty("hostName")  // property set elsewhere

So my question is whether anyone has a workaround for this? It does not have to be using @ConditionalOnProperty, although I like that solution.

Ryan Dawson :

I think you could use @Conditional with a custom Condition. Or at the beginning of your @Scheduled method you could have an if statement that checks the hostname (e.g. using InetAddress.getLocalHost().getHostName()) against the value you are looking for.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108627&siteId=1