Propiedades en Spring Boot
- Idea clave
- Spring Boot carga las propiedades de muchas fuentes (ficheros `application.properties`/`.yml`, ficheros por perfil, variables de entorno, propiedades del sistema, argumentos…) en un orden fijo de precedencia, y `@ConfigurationProperties` las vuelca en un objeto con tipos, valores por defecto y validación.
- En el box
- La configuración del box estaba repartida en decenas de @Value con el prefijo repetido y sin validar. Agrúpala en un record con @ConfigurationProperties, aprende dónde busca Boot las propiedades y en qué orden, cómo funcionan los perfiles y el relaxed binding, y cómo validar al arrancar.
El Environment rellena ValueBasedSettings, resaltado en rojo, con un @Value por cada propiedad.
El fichero application.yml, fuera del contexto y resaltado junto al Environment, se carga al arrancar.
El Environment pasa box.* al Binder, que crea el BoxProperties; los dos están resaltados.
El Binder entrega a BoxProperties, resaltado, el valor "60m" ya convertido en Duration.
El Binder, resaltado, recibe maxAthletes y lo enlaza como si fuera max-athletes.
application-prod.yml, resaltado, aporta max-athletes 20 al Environment, que gana a application.yml.
El argumento --box.max-athletes=40, resaltado junto al Environment, gana a los ficheros YAML.
El Binder pide a Bean Validation, resaltado, que compruebe @Min(1); falla y la aplicación no arranca.
Vista final: los ficheros y argumentos fuera, el Environment, el Binder, BoxProperties con su validación y BoxInfoService dentro del contexto.
Paso 1 de 9
Un @Value por propiedad
ValueBasedSettings lee la configuración del box con un @Value por propiedad:
- El prefijo
box.se repite en cada línea, y una errata solo se descubre al arrancar (o peor, se queda sin resolver). class-durationllega comoStringy hay que convertirla a mano.- Nadie comprueba que
max-athletestenga sentido.
Paso 2 de 9
application.yml y dónde lo busca Boot
Spring Boot carga solo los ficheros application.properties o application.yml. Los busca en classpath:/, classpath:/config/, el directorio actual y ./config/ (los de fuera del jar tienen más prioridad).
box:
name: CrossFit Norte
max-athletes: 12
class-duration: 60m
plans: [monthly, ten-pack, drop-in]
address:
city: Madrid
YAML permite jerarquías y listas sin repetir prefijos. Para traer más ficheros, spring.config.import=optional:file:./secrets.yml.
Paso 3 de 9
@ConfigurationProperties
BoxProperties es un record anotado con @ConfigurationProperties(prefix = "box"). El Binder de Boot coge todas las propiedades box.* y las vuelca en él por nombre:
box.name→name,box.max-athletes→maxAthletes…- Al ser un record, se enlaza por constructor: un objeto inmutable. Una clase con setters también vale.
- Se registra como bean con
@ConfigurationPropertiesScanen la aplicación (o@EnableConfigurationProperties(BoxProperties.class)), y se inyecta como cualquier otro:BoxInfoService(BoxProperties box).
Paso 4 de 9
Tipos, listas y objetos anidados
El Binder convierte el texto al tipo de cada campo:
int maxAthletes←"12".Duration classDuration←"60m"(tambiénPT45M,30s,2h). Con@DefaultValue("60m"), si falta la propiedad.List<String> plans← una lista YAML (o"a,b,c").Address address←box.address.*: un objeto anidado. Con@Valid, también se validan sus campos.
Hay conversores para DataSize (10MB), enumeraciones, Map, etc. El test comprueba cada uno.
Paso 5 de 9
Relaxed binding
Boot acepta varias formas de escribir el mismo nombre:
box.max-athletes(kebab-case, la forma canónica, recomendada en ficheros).box.maxAthletes(camelCase),box.max_athletes.BOX_MAXATHLETEScomo variable de entorno (mayúsculas, el punto pasa a_, sin guiones).
El test usa box.maxAthletes=25 y una duración ISO (PT45M), y los dos llegan.
Paso 6 de 9
Ficheros por perfil
Con el perfil prod activo, Boot carga además application-prod.yml, que gana a application.yml:
box.max-athletespasa a 20.- El resto (
name,address…) sigue saliendo deapplication.yml.
El perfil se activa con spring.profiles.active=prod (en un fichero, como -D, como variable SPRING_PROFILES_ACTIVE o como argumento) o con @ActiveProfiles en los tests. En un solo YAML puedes separar documentos con --- y spring.config.activate.on-profile: prod.
Paso 7 de 9
¿Quién gana? El orden en Boot
Boot ordena sus fuentes de propiedades. Resumen, de más a menos prioridad:
- Propiedades de los tests (
@TestPropertySource,@SpringBootTest(properties = …)). - Argumentos de línea de comandos (
--box.max-athletes=40). SPRING_APPLICATION_JSON.- Propiedades del sistema de Java (
-D). - Variables de entorno.
- Ficheros de configuración: de perfil fuera del jar > de perfil dentro > generales fuera > generales dentro.
@PropertySource.- Valores por defecto (
SpringApplication.setDefaultProperties).
El test lo comprueba: -D (30) gana a los dos YAML, y el argumento (40) gana a todo.
Paso 8 de 9
Validar al arrancar
Con @Validated en la clase de propiedades y anotaciones de Bean Validation (@NotBlank, @Min, @Max…), el Binder valida al enlazar. Con box.max-athletes=0 la aplicación no arranca, y el error dice qué propiedad incumple qué regla: box.maxAthletes, «must be greater than or equal to 1».
Paso 9 de 9
Resumen
- Ficheros:
application.properties/.ymlyapplication-{perfil}.yml. - Orden: tests > línea de comandos >
-D> entorno > ficheros (perfil > general, fuera > dentro) >@PropertySource. @ConfigurationProperties(prefix)+@ConfigurationPropertiesScan: tipos, listas, anidados,@DefaultValue.- Relaxed binding:
max-athletes=maxAthletes=BOX_MAXATHLETES. @Validated: el arranque falla con valores inválidos.
Código
ValueBasedSettings.java
/** Before: one @Value per setting, the prefix repeated everywhere, and no validation. */
public class ValueBasedSettings {
@Value("${box.name}") String name;
@Value("${box.max-athletes}") int maxAthletes;
@Value("${box.class-duration}") String classDuration; // a String: convert it yourself
@Value("${box.address.city}") String city;
// …one more line, and one more chance of a typo, for every property
}BindingTest.java
@Test
void typedBindingFromApplicationYml() {
assertThat(box.name()).isEqualTo("CrossFit Norte");
assertThat(box.maxAthletes()).isEqualTo(12); // "12" → int
assertThat(box.classDuration()).isEqualTo(Duration.ofMinutes(60)); // "60m" → Duration
assertThat(box.plans()).containsExactly("monthly", "ten-pack", "drop-in");
assertThat(box.address().city()).isEqualTo("Madrid"); // nested record
}BoxProperties.java
@ConfigurationProperties(prefix = "box") // binds box.* onto this record, by name
@Validated // Bean Validation at startup
public record BoxProperties(
@NotBlank String name,
@Min(1) @Max(50) int maxAthletes, // box.max-athletes, box.maxAthletes, BOX_MAXATHLETES…
@DefaultValue("60m") Duration classDuration, // "60m" → Duration.ofMinutes(60)
List<String> plans, // YAML list or "a,b,c"
@Valid Address address) { // nested object: box.address.*
public record Address(String street, @NotBlank String city) {
}
}BoxProperties.java
@ConfigurationProperties(prefix = "box") // binds box.* onto this record, by name
@Validated // Bean Validation at startup
public record BoxProperties(
@NotBlank String name,
@Min(1) @Max(50) int maxAthletes, // box.max-athletes, box.maxAthletes, BOX_MAXATHLETES…
@DefaultValue("60m") Duration classDuration, // "60m" → Duration.ofMinutes(60)
List<String> plans, // YAML list or "a,b,c"
@Valid Address address) { // nested object: box.address.*
public record Address(String street, @NotBlank String city) {
}
}RelaxedBindingTest.java
@SpringBootTest(properties = {
"box.maxAthletes=25", // camelCase works too (relaxed binding)…
"box.class-duration=PT45M"}) // …and ISO-8601 durations
class RelaxedBindingTest {
@Autowired
BoxProperties box;
@Test
void manySpellingsOneProperty() {
assertThat(box.maxAthletes()).isEqualTo(25);
assertThat(box.classDuration().toMinutes()).isEqualTo(45);
}
}ProfileFileTest.java
@SpringBootTest
@ActiveProfiles("prod") // loads application-prod.yml on top of application.yml
class ProfileFileTest {
@Autowired
BoxProperties box;
@Test
void theProfileSpecificFileWins() {
assertThat(box.maxAthletes()).isEqualTo(20); // from application-prod.yml
assertThat(box.name()).isEqualTo("CrossFit Norte"); // still from application.yml
}
}PrecedenceAndValidationTest.java
@Test
void commandLineBeatsSystemPropertiesWhichBeatTheFiles() {
System.setProperty("box.max-athletes", "30"); // -Dbox.max-athletes=30
try (var ctx = app().profiles("prod").run()) {
assertThat(ctx.getBean(BoxProperties.class).maxAthletes()).isEqualTo(30); // beats both yml files
}
try (var ctx = app().profiles("prod").run("--box.max-athletes=40")) {
assertThat(ctx.getBean(BoxProperties.class).maxAthletes()).isEqualTo(40); // command line wins
}
}PrecedenceAndValidationTest.java
@Test
void invalidValuesStopTheApplicationAtStartup() {
assertThatThrownBy(() -> app().run("--box.max-athletes=0").close()) // @Min(1)
.hasStackTraceContaining("box.maxAthletes")
.hasStackTraceContaining("must be greater than or equal to 1");
}BoxProperties.java
@ConfigurationProperties(prefix = "box") // binds box.* onto this record, by name
@Validated // Bean Validation at startup
public record BoxProperties(
@NotBlank String name,
@Min(1) @Max(50) int maxAthletes, // box.max-athletes, box.maxAthletes, BOX_MAXATHLETES…
@DefaultValue("60m") Duration classDuration, // "60m" → Duration.ofMinutes(60)
List<String> plans, // YAML list or "a,b,c"
@Valid Address address) { // nested object: box.address.*
public record Address(String street, @NotBlank String city) {
}
}