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.
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:
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
}
@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);
}
}
}
@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
}
// 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;
}
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);
}
}
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.
class SpringDependencyInjectionConstructorSetterFieldInjectionReview {
public static void main(String[] args) {
String state = "ready";
System.out.println("Spring Dependency Injection Constructor Setter Field Injection: " + state);
}
}
String value = null;
if (value == null) {
System.out.println("Spring Dependency Injection Constructor Setter Field Injection: handle the missing value before continuing");
}
Memorizing Spring Dependency Injection Constructor Setter Field Injection without the situation where it is useful.
Connect Spring Dependency Injection Constructor Setter Field Injection to a concrete Spring task.
Testing Spring Dependency Injection Constructor Setter Field Injection only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Spring Dependency Injection Constructor Setter Field Injection.
Memorizing Spring Dependency Injection Constructor Setter Field Injection without the situation where it is useful.
Connect Spring Dependency Injection Constructor Setter Field Injection to a concrete Spring task.
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.
Explore 500+ free tutorials across 20+ languages and frameworks.