If you have a Spring component and you don't want it to load, you can use Spring's predefined conditionals as much as possible.
For example,
But sometimes you want to use custom conditions. It's pretty easy to do so, just use something like this
Basically you write a class that implements the Condition interface from Spring and use it in the @Conditional annotation. Of course this example has an inner class but you get the idea.
So in this example, this component will be disabled if 'scheduler' system property is not set.
Simple, but powerful.
Spring away!
For example,
@Component
@ConditionalOnNotWebApplication
public class SchedulerEntryPoint implements ApplicationRunner { ...
This will not load your component when running in non web application mode. Such as you may want to start the application but without any of the web framework using SpringApplicationBuilder.}
But sometimes you want to use custom conditions. It's pretty easy to do so, just use something like this
@Component@Conditional(SchedulerCheck.class) public class SchedulerEntryPoint implements ApplicationRunner { public static class SchedulerCheck implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return System.getProperty("scheduler") != null; } }
...}
Basically you write a class that implements the Condition interface from Spring and use it in the @Conditional annotation. Of course this example has an inner class but you get the idea.
So in this example, this component will be disabled if 'scheduler' system property is not set.
You can also use more than one conditional of course.
Simple, but powerful.
Spring away!
Comments
Post a Comment