Tutorials Logic, IN info@tutorialslogic.com

Spring Dependency Injection Constructor, Setter, Field Injection: Tutorial, Examples, FAQs & Interview Tips

Spring Dependency Injection Constructor, Setter, Field Injection

Spring Dependency Injection Constructor, Setter, Field Injection is an important Spring topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Spring Dependency Injection Constructor, Setter, Field Injection solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Spring Dependency Injection Constructor, Setter, Field Injection should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Spring Dependency Injection Constructor Setter Field Injection should be studied as a practical Spring lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the spring > dependency-injection page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

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

IoC and Dependency Injection
@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

IoC and Dependency Injection
@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);
    }
}

Detailed Learning Notes for Spring Dependency Injection Constructor, Setter, Field Injection

When studying Spring Dependency Injection Constructor, Setter, Field Injection, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Spring, Spring Dependency Injection Constructor, Setter, Field Injection becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Spring Dependency Injection Constructor Setter Field Injection Java review example

Spring Dependency Injection Constructor Setter Field Injection Java review example
class SpringDependencyInjectionConstructorSetterFieldInjectionReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Spring Dependency Injection Constructor Setter Field Injection: " + state);
    }
}

Spring Dependency Injection Constructor Setter Field Injection guard example

Spring Dependency Injection Constructor Setter Field Injection guard example
String value = null;
if (value == null) {
    System.out.println("Spring Dependency Injection Constructor Setter Field Injection: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Spring Dependency Injection Constructor, Setter, Field Injection before memorizing syntax.
  • Run or trace one small Spring example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Spring Dependency Injection Constructor, Setter, Field Injection.
  • Write the rule in your own words after checking the example.
  • Connect Spring Dependency Injection Constructor, Setter, Field Injection to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Spring Dependency Injection Constructor Setter Field Injection without the situation where it is useful.
RIGHT Connect Spring Dependency Injection Constructor Setter Field Injection to a concrete Spring task.
Purpose makes syntax easier to recall.
WRONG Testing Spring Dependency Injection Constructor Setter Field Injection only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Spring Dependency Injection Constructor Setter Field Injection.
Evidence keeps debugging focused.
WRONG Memorizing Spring Dependency Injection Constructor Setter Field Injection without the situation where it is useful.
RIGHT Connect Spring Dependency Injection Constructor Setter Field Injection to a concrete Spring task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Spring Dependency Injection Constructor, Setter, Field Injection, then fix it and explain the fix.
  • Summarize when to use Spring Dependency Injection Constructor, Setter, Field Injection and when another approach is better.
  • Write a small example that uses Spring Dependency Injection Constructor Setter Field Injection in a realistic Spring scenario.
  • Change one important value in the Spring Dependency Injection Constructor Setter Field Injection example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Spring, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

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