Conditional configuration


When you add Spring Boot to your application, there’s a JAR file named springboot-autoconfigure that contains several configuration classes. Every one of these configuration classes is available on the application’s classpath and has the opportunity to contribute to the configuration of your application.

Conditional configuration allows for configuration to be available in an application, but to be ignored unless certain conditions are met.

 It’s easy enough to write your own conditions in Spring. All you have to do is implement the Condition interface and override its matches() method.

For example, the following simple condition class will only pass if JdbcTemplate is available on the classpath:

import org.springframework.context.annotation.Condition;

import org.springframework.context.annotation.ConditionContext;

import org.springframework.core.type.AnnotatedTypeMetadata;

public class JdbcTemplateCondition implements Condition {

@Override

public boolean matches(ConditionContext context,

AnnotatedTypeMetadata metadata) 

{

try {

context.getClassLoader().loadClass(

"org.springframework.jdbc.core.JdbcTemplate");

return true;

} catch (Exception e) {

return false;

}

}