Sub topic 8
What gets fixed at build time
This chapter assumes you know Spring Boot auto-configuration, @Conditional annotations, profiles, and how to build a project with Maven or Gradle. It also assumes you have read the earlier chapters on Spring AOT processing and the closed-world assumption.
On the JVM, Spring decides which beans exist while the application starts. In a native executable, much of that decision has already been made. The decision happens during the build, and the executable only carries the result. This chapter covers what is frozen, what stays dynamic, and how to avoid surprises.
Why the bean set is frozen
A normal Spring Boot application builds its bean definitions at startup. It scans the classpath, reads annotations, evaluates conditions, and registers beans, mostly through reflection. That is flexible, but it needs reflection and class loading, which the native-image tool cannot analyze ahead of time.
Spring AOT processing replaces this work. During the build, Spring starts a version of your application context that only collects bean definitions. It evaluates conditions against the build-time environment, then generates plain Java source code that registers exactly the beans that survived. That code is compiled and passed to native-image.
The consequence is simple. If a bean was not registered during AOT processing, the native executable contains no code to create it. No runtime setting can add it later.
What is fixed
These decisions are made at AOT time and cannot change in the executable:
- Conditions on properties.
@ConditionalOnPropertyis evaluated against the properties visible during AOT processing. - Conditions on classes.
@ConditionalOnClassand@ConditionalOnMissingClasslook at the build classpath. The executable has no classpath to inspect later. - Conditions on beans.
@ConditionalOnBeanand@ConditionalOnMissingBeandepend on the set of definitions at build time. That set is fixed, so these results are fixed too. - Profiles.
@Profileis a condition, so the active profiles during AOT processing decide which profile-specific beans exist. - Bean definitions in general. A bean cannot be defined dynamically at runtime through a mechanism the AOT step could not see, such as a
BeanFactoryPostProcessorthat registers types based on runtime data. - Auto-configuration. The set of auto-configurations that apply is decided at build time. Each one's internal conditions are fixed with it.
A conditional bean, step by step
The configuration below creates FeatureService only when app.feature.enabled is true.
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeatureConfig {
@Bean
@ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true")
public FeatureService featureService() {
return new FeatureService();
}
public static class FeatureService {}
}Suppose src/main/resources/application.properties does not set app.feature.enabled. You build the native executable and then start it like this:
./target/demo --app.feature.enabled=trueOn the JVM, this would create the bean. In the native executable, it does not. The condition was evaluated during the build, found no property, and Spring generated no registration code for featureService. Any component that injects FeatureService fails at startup with a missing-bean error.
The reverse also holds. If the property was true at build time and you start with --app.feature.enabled=false, the bean still exists.
The fix is to set the property during the build. Put it in application.properties, or pass it to the AOT step. Treat the value as a property of the build artifact, as you would a compile-time constant.
Setting build-time profiles
Profiles work the same way. If you run ./mvnw -Pnative native:compile with no active profile, only beans for the default profile are compiled in. Starting the executable with --spring.profiles.active=production will not bring in beans annotated @Profile("production").
Tell the AOT step which profiles to use. With Maven, configure the process-aot execution of the Spring Boot plugin:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>process-aot</id>
<configuration>
<profiles>production</profiles>
</configuration>
</execution>
</executions>
</plugin>With Gradle, pass the argument to the ProcessAot task:
tasks.withType<org.springframework.boot.gradle.tasks.aot.ProcessAot>().configureEach {
args("--spring.profiles.active=production")
}Then build as usual:
./mvnw -Pnative native:compileThis means one native executable corresponds to one profile selection. If you ship the same application for dev, staging and production with different bean sets, you build three executables. Profile-specific property files can still be read at runtime, but beans that depend on a profile condition cannot be switched.
What stays dynamic
Not everything is frozen. These still work at runtime:
- Values bound to existing beans.
@Value("${...}")and@ConfigurationPropertiesread the runtimeEnvironment. Environment variables, command-line arguments, and externalapplication.propertiesfiles can change a port, a URL or a timeout. - Logic inside method bodies. Ordinary Java code in a bean method or constructor runs at runtime. An
ifon a property value works. - Data. Anything your code reads from files, databases or the network behaves as on the JVM, subject to the resource and reflection rules from the metadata chapters.
The distinction to keep in mind is that properties can change what a bean does, but they cannot change whether the bean exists, if that decision is made by a condition.
Making a feature switch work at runtime
If you need a toggle that operations can flip without rebuilding, move the decision from a condition into a bean's behavior. Register the bean always, and read the flag at runtime.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class FeatureGate {
private final boolean enabled;
public FeatureGate(@Value("${app.feature.enabled:false}") boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
}Callers check featureGate.isEnabled() before using the feature. The bean always exists, and the flag is read when the executable starts. This costs a little memory for the feature's code, which you were probably going to pay anyway for a feature you might enable.
Use build-time conditions when the choice should remove code, for example to leave out an integration the deployment never uses. Use a runtime flag when the same executable must serve different settings.
Inspecting what AOT decided
You can see the output of AOT processing. After a build, look in target/spring-aot/main/sources for Maven, or under build/generated/aotSources for Gradle. You will find generated classes with names such as FeatureConfig__BeanDefinitions. When a conditional bean is missing from the executable, check whether its __BeanDefinitions method exists in the generated sources. If it does not, the condition evaluated to false during the build.
You can also reproduce the problem on the JVM before spending minutes on a native compile. Run the app with AOT-generated code enabled:
java -Dspring.aot.enabled=true -jar target/demo.jarThe JVM then uses the generated bean definitions instead of scanning. If the bean is missing here, the cause is the build-time condition, not a native-image limitation.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` only in the native executable | A conditional bean evaluated to false at build time | Set the property or profile for the AOT step |
| A `@Profile` bean is missing despite `--spring.profiles.active` at startup | Profile was not active during AOT processing | Configure `profiles` for `process-aot`, or the Gradle `ProcessAot` argument |
| A feature flag set in the container environment has no effect | The flag drives a `@ConditionalOnProperty` | Use a runtime flag, as in `FeatureGate` |
| Different environments behave identically | One executable was built with one profile | Build one executable per profile set |
Summary
Spring AOT evaluates conditions once, during the build, and generates code for the beans that remain. Properties, profiles and the classpath used in that build define the bean set of the executable. Values bound to existing beans and logic inside method bodies still use the runtime environment. When you need an operator-controlled switch, register the bean unconditionally and read the flag at runtime.
Exercise
A service uses @Profile("cloud") on a CloudStorage bean and @Profile("local") on a LocalStorage bean. You build one native executable with no profile configured for AOT processing, then start it with --spring.profiles.active=cloud. The application fails with a missing CloudStorage bean. Why does this happen, and give two ways to fix it?
Show answer
@Profile is evaluated during AOT processing. With no profile active in that step, only the default-profile beans were registered, so no registration code for CloudStorage was generated and the runtime profile cannot add it. Fix 1: set the profile for the AOT step (<profiles>cloud</profiles> for the Maven process-aot execution, or args("--spring.profiles.active=cloud") on the Gradle ProcessAot task) and rebuild. Fix 2: replace the two profile-based beans with one bean that reads a runtime property such as @Value("${storage.mode}") and chooses its behavior in code, so a single executable serves both modes.
Exercise
You run java -Dspring.aot.enabled=true -jar target/demo.jar and a @ConditionalOnProperty bean is missing. What does this tell you about the cause, and why is this check useful before a native build?
Show answer
It shows the bean is missing because of the AOT-time condition result, not because of a native-image limitation such as missing reflection metadata. The JVM runs the same generated bean definitions, so you reproduce the problem in seconds instead of waiting for a native compile, then fix the property or profile used during AOT processing.