@Conditional conditional bean
Spring support bean creation if certain condition meet.
For that you required to implement below interface
public interface Condition {
boolean matches(ConditionContext ctxt, AnnotatedTypeMetadata metadata);
}
Example:
public MyBeanContition implements Condition{
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
Environment env = context.getEnvironment();
return env.containsProperty("server.instance");
}
}
@Configuration
class ServerInstance{
@Conditional(MyBeanCondition.class)
public ServerData getServerData(){
return new ServerData();
}
}
Here the ServerData bean will be created only if the environment contains the
server.instance property.
Same way you can also check for particular bean property, resource properties or environment
property etc.