Tutorials Logic, IN info@tutorialslogic.com

Spring Dependency Injection Constructor, Setter, Field Injection

Constructor Dependencies

Dependency injection means an object receives collaborators instead of locating or constructing them internally. Constructor injection makes required dependencies visible, supports immutable fields, and lets a plain unit test construct the object directly. Spring resolves constructor arguments by type and uses qualifiers when several candidates match.

IoC and Dependency Injection

Inversion of Control (IoC) is a design principle where the control of object creation and lifecycle is transferred from the application code to a container (the Spring IoC container). Dependency Injection (DI) is the mechanism Spring uses to implement IoC - it injects dependencies into objects rather than having objects create their own dependencies.

Spring supports three types of dependency injection:

  • Constructor Injection - Dependencies injected via constructor (recommended)
  • Setter Injection - Dependencies injected via setter methods
  • Field Injection - Dependencies injected directly into fields via @Autowired

Constructor, Setter, and Field Injection

Constructor, Setter, and Field Injection
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class OrderService {
    private final UserRepository userRepository;
    private final EmailService emailService;
    private final PaymentService paymentService;

    // Constructor injection - RECOMMENDED
    // @Autowired is optional when there's only one constructor (Spring 4.3+)
    @Autowired
    public OrderService(UserRepository userRepository,
                        EmailService emailService,
                        PaymentService paymentService) {
        this.userRepository = userRepository;
        this.emailService   = emailService;
        this.paymentService = paymentService;
    }

    // Benefits:
    // 1. Dependencies are immutable (final fields)
    // 2. Mandatory dependencies are explicit
    // 3. Easy to test (just pass mocks to constructor)
    // 4. Detects circular dependencies at startup
}

IoC and Dependency Injection - Java Example

IoC and Dependency Injection - Java Example
@Service
public class NotificationService {
    private EmailService emailService;
    private SmsService smsService;

    // Setter injection - for optional dependencies
    @Autowired
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }

    @Autowired(required = false) // Optional dependency
    public void setSmsService(SmsService smsService) {
        this.smsService = smsService;
    }

    public void notify(String message) {
        emailService.send(message);
        if (smsService != null) {
            smsService.send(message);
        }
    }
}

IoC and Dependency Injection - Java Example 2

IoC and Dependency Injection - Java Example 2
@Service
public class ProductService {
    // Field injection - NOT recommended for production
    // (harder to test, hides dependencies, can't use final)
    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private CacheService cacheService;

    // Works but considered bad practice
    // Use constructor injection instead
}

@Qualifier, @Primary, and @Value

@Qualifier, @Primary, @Value

@Qualifier, @Primary, @Value
// When multiple beans of the same type exist, use @Qualifier or @Primary

// Two implementations of NotificationService
@Service("emailNotification")
public class EmailNotificationService implements NotificationService { ... }

@Service("smsNotification")
@Primary // This one is injected by default when no @Qualifier is specified
public class SmsNotificationService implements NotificationService { ... }

// Injecting with @Qualifier
@Service
public class AlertService {
    private final NotificationService emailService;
    private final NotificationService smsService;

    @Autowired
    public AlertService(
            @Qualifier("emailNotification") NotificationService emailService,
            @Qualifier("smsNotification")   NotificationService smsService) {
        this.emailService = emailService;
        this.smsService   = smsService;
    }
}

// @Value: inject values from application.properties
@Service
public class AppConfigService {
    @Value("${app.name}")
    private String appName;

    @Value("${app.version:1.0}") // Default value if property not found
    private String version;

    @Value("${server.port}")
    private int port;

    @Value("${app.features:feature1,feature2}") // Comma-separated list
    private List<String> features;
}

@Configuration and @Bean

Java-based Configuration

Java-based Configuration
import org.springframework.context.annotation.*;
import org.springframework.beans.factory.annotation.Value;

@Configuration // Marks this as a Spring configuration class
public class AppConfig {

    @Value("${app.name}")
    private String appName;

    // @Bean: manually define a bean (useful for third-party classes)
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean(name = "customObjectMapper")
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    // Bean with dependency on another bean
    @Bean
    public EmailService emailService(MailSender mailSender) {
        return new EmailServiceImpl(mailSender, appName);
    }
}

Ambiguous Dependencies

A single constructor does not need @Autowired. When two beans implement the same interface, use a meaningful @Qualifier, @Primary, or @Fallback policy rather than injecting a collection accidentally or renaming fields until resolution happens. Optional dependencies should represent a genuine optional capability, not hide incomplete configuration.

Field injection obscures requirements and makes non-container tests awkward. Setter injection fits an optional reconfigurable collaborator but permits a partially initialized object unless the class defends that state. Keep configuration values in typed configuration objects instead of scattering @Value strings.

Before you move on

Spring Dependency Injection Constructor, Setter, Field Injection Mastery Check

3 checks
  • Inversion of Control (IoC) is a design principle where the control of object creation and lifecycle is transferred from the application code to a container (the Spring IoC container).
  • Dependency Injection (DI) is the mechanism Spring uses to implement IoC - it injects dependencies into objects rather than having objects create their own dependencies.
  • Prefer constructor injection, then test the bean with a deliberately chosen implementation.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.