Chuleta

Propiedades, perfiles y SpEL

Idea clave

La configuración que cambia entre entornos vive fuera del código. El `Environment` de Spring junta varias fuentes de propiedades (ficheros, variables de entorno, propiedades del sistema) y sabe qué perfiles están activos; `@Value` inyecta sus valores y `@Profile` decide qué beans existen.

Diagrama (UML)

ApplicationContextcoachRosterbox.propertiesEnvironmentBoxSettings-Dbox.name=…WelcomeServiceConsoleMailer (dev, default)SmtpMailer (prod)

Piezas clave

  • @PropertySource("classpath:box.properties"): añade un fichero al Environment
  • Environment: getProperty(key), getProperty(key, default), getProperty(key, Type), getRequiredProperty(key), getActiveProfiles()
  • @Value("${clave:porDefecto}"): marcador de propiedad; @Value("#{expresión}"): SpEL
  • PropertySourcesPlaceholderConfigurer: resuelve los ${…} de forma estricta; se declara con un @Bean static
  • @Profile("prod"), @Profile({"dev", "default"}), @Profile("!prod"), @Profile("dev & cloud")
  • Activar perfiles: spring.profiles.active, env.setActiveProfiles(), @ActiveProfiles en tests

BoxSettings.java

public BoxSettings(@Value("${box.name}") String name,                // ${…}: a property placeholder
                   @Value("${box.capacity:10}") int capacity,       // ":10" is the default if missing
                   @Value("#{'${box.plans}'.split(',')}") List<String> plans, // split "a,b,c" with SpEL
                   @Value("#{${box.capacity} * 2}") int waitlist,             // #{…}: SpEL, placeholder inside
                   @Value("#{coachRoster.size() * 6}") int classesPerDay,      // a bean, by name
                   @Value("#{systemProperties['box.tz'] ?: 'Europe/Madrid'}") String timezone) { // Elvis
                       // …
                   }

Recuerda para el examen

  • ${…} lee una propiedad; #{…} evalúa una expresión SpEL; se pueden anidar: #{${box.capacity} * 2}
  • En SpEL, un bean se referencia por su nombre: #{coachRoster.size()}; una clase con T(java.lang.Math)
  • Variables útiles de SpEL: systemProperties, systemEnvironment; operador Elvis ?: y navegación segura ?.
  • En Spring a secas, las propiedades del sistema (-D) ganan a las variables de entorno, y estas a @PropertySource
  • Si no hay ningún perfil activo, se activa el perfil default
  • Los perfiles se activan antes de refrescar el contexto; cambiarlos después no tiene efecto

Trampas de examen

  • Sin PropertySourcesPlaceholderConfigurer, un ${clave} que no existe se queda tal cual, como texto literal; con él (y en Spring Boot), el arranque falla
  • El @Bean de PropertySourcesPlaceholderConfigurer debe ser static; si no, se crea tarde y los @Value de esa clase no se resuelven
  • En Spring a secas, @Value("${lista}") List<String> no separa por comas (recibes un solo elemento); usa String[], SpEL .split(',') o Spring Boot
  • getProperty devuelve null si falta la clave; getRequiredProperty lanza IllegalStateException
  • Un bean sin @Profile existe siempre, con cualquier perfil activo

← Propiedades, perfiles y SpEL · Ejecútalo