Spring Boot Autoconfiguration Trick - excluding Autoconfiguration based on Profile
Doing a bit of hacking in Spring AI and wanted to kill of autoconfiguration based on profiles.
Maybe a little hacky but below is what worked.
Basics
- doesn’t start using direct
SpringApplication.runbut instead uses theSpringApplicationBuilder - this allows access to the profiles before starting
- setting the property based on profiles to exclude the autoconfiguration
I’m sure there are better ways but this was expedient and a nice little programmatic trick!
package ai.someexamplesof.agent;
import org.springframework.ai.model.ollama.autoconfigure.OllamaChatAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class Application {
public static void main(String... args) throws Exception {
// SpringApplication.run(Application.class,args);
String activeProfile = System.getProperty("spring.profiles.active","");
SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
//check
if (!"ollama".equalsIgnoreCase(activeProfile)) {
builder.properties(
"spring.autoconfigure.exclude=" + OllamaChatAutoConfiguration.class.getName()
);
} //end if
builder.run(args);
}
}