← Kursa Dön
📄 Text · 18 min

@Value ve @ConfigurationProperties

Giriş

Uygulama konfigürasyonunu kod içine gömmek yerine harici dosyalardan okumak, 12-Factor App prensiplerinden biridir. Spring Boot, application.properties veya application.yml dosyalarından değer okumak için @Value ve @ConfigurationProperties olmak üzere iki yaklaşım sunar.

@Value — Basit Değer Injection

@Value ile tekil konfigürasyon değerlerini doğrudan enjekte edebilirsiniz:

@Service
public class EmailService {

    @Value("${app.email.from}")
    private String fromAddress;

    @Value("${app.email.max-retries:3}")  // Varsayılan: 3
    private int maxRetries;

    @Value("${app.email.enabled:true}")
    private boolean enabled;
}
# application.properties
app.email.from=noreply@myapp.com
app.email.max-retries=5
app.email.enabled=true

@Value ile Constructor Injection

@Service
public class EmailService {
    private final String fromAddress;
    private final int maxRetries;

    public EmailService(
            @Value("${app.email.from}") String fromAddress,
            @Value("${app.email.max-retries:3}") int maxRetries) {
        this.fromAddress = fromAddress;
        this.maxRetries = maxRetries;
    }
}

SpEL (Spring Expression Language)

@Value içinde SpEL ifadeleri kullanabilirsiniz:

// Sistem ortam değişkeni
@Value("#{systemEnvironment['HOME']}")
private String homeDir;

// Koşullu değer
@Value("#{${app.feature.enabled} ? 'active' : 'inactive'}")
private String featureStatus;

// Matematiksel ifade
@Value("#{${app.base-price} * 1.18}")
private double priceWithTax;

// Bean referansı
@Value("#{appConfig.getDefaultTimeout()}")
private int timeout;

// Liste
@Value("${app.allowed-origins}")
private List<String> allowedOrigins;
// app.allowed-origins=http://localhost:3000,https://myapp.com

@ConfigurationProperties — Type-Safe Binding

@ConfigurationProperties, bir properties prefix'ine karşılık gelen tüm değerleri bir Java sınıfına bağlar. Bu yaklaşım @Value'den çok daha güçlü ve güvenlidir:

@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
    private String host;
    private int port = 587;
    private String username;
    private String password;
    private boolean starttls = true;
    private Retry retry = new Retry();

    // Nested class
    public static class Retry {
        private int maxAttempts = 3;
        private long delay = 1000;
        // getter/setter
    }

    // getter/setter (veya Lombok @Data)
}
# application.yml
app:
  mail:
    host: smtp.gmail.com
    port: 587
    username: user@gmail.com
    password: secret
    starttls: true
    retry:
      max-attempts: 5
      delay: 2000

Aktifleştirme

// Yöntem 1: @EnableConfigurationProperties
@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class MailConfig { }

// Yöntem 2: @ConfigurationPropertiesScan (Boot 2.2+)
@SpringBootApplication
@ConfigurationPropertiesScan
public class MyApplication { }

// Yöntem 3: @Component ile (en basit)
@Component
@ConfigurationProperties(prefix = "app.mail")
public class MailProperties { }

Kullanım

@Service
@RequiredArgsConstructor
public class MailService {
    private final MailProperties mailProperties;

    public void sendEmail(String to, String subject, String body) {
        System.out.println("Sending from: " + mailProperties.getHost());
        System.out.println("Max retries: " + mailProperties.getRetry().getMaxAttempts());
    }
}

Validation ile Birlikte Kullanım

@ConfigurationProperties bean'lerini @Validated ile doğrulayabilirsiniz:

@Validated
@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {

    @NotBlank(message = "Mail host boş olamaz")
    private String host;

    @Min(1) @Max(65535)
    private int port = 587;

    @NotBlank
    private String username;

    // Uygulama başlarken validasyon hatası varsa başlamaz!
}

@Value vs @ConfigurationProperties Karşılaştırma

Özellik@Value@ConfigurationProperties
KullanımTek tek değerlerPrefix altındaki tüm değerler
Type safetyDüşük (string-based)Yüksek (Java sınıfı)
Nested propertiesDesteklemezTam destek
ValidationSınırlı@Validated ile tam destek
IDE desteğiSınırlıTam (auto-complete)
Relaxed bindingYokVar (kebab-case ↔ camelCase)
Meta-dataYokspring-configuration-metadata.json

Relaxed Binding

@ConfigurationProperties aşağıdaki formatları otomatik eşleştirir:

# Hepsi aynı alanı set eder:
app.mail.max-attempts=5     # kebab-case (önerilen)
app.mail.maxAttempts=5       # camelCase
app.mail.max_attempts=5      # underscore
APP_MAIL_MAXATTEMPTS=5       # UPPER_CASE (env variable)

Best Practices

İpucu: Tekil, basit değerler için @Value, ilişkili bir değer grubu için @ConfigurationProperties kullanın. Büyük projelerde @ConfigurationProperties tercih edin.

Uyarı: Hassas bilgileri (şifre, API key) application.properties'e yazmayın. Ortam değişkenleri veya Vault gibi secret management araçları kullanın.

Özet

@Value basit değer injection'ı için, @ConfigurationProperties type-safe, hiyerarşik konfigürasyon binding'i için kullanılır. Production uygulamalarda @ConfigurationProperties + @Validated kombinasyonu en güvenli ve bakımı en kolay yaklaşımdır.