0% found this document useful (0 votes)
6 views5 pages

Spring Boot @Autowired Dependency Injection

@Autowired is a Spring annotation for automatic dependency injection, reducing boilerplate code and promoting loose coupling. It supports three types of injection: field, constructor (preferred), and setter, with @Primary and @Qualifier used to handle multiple beans of the same type. Constructor injection is favored for its support of immutability and easier testing, while @Primary marks a default bean and @Qualifier specifies which bean to inject.

Uploaded by

gopal6291441556
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Spring Boot @Autowired Dependency Injection

@Autowired is a Spring annotation for automatic dependency injection, reducing boilerplate code and promoting loose coupling. It supports three types of injection: field, constructor (preferred), and setter, with @Primary and @Qualifier used to handle multiple beans of the same type. Constructor injection is favored for its support of immutability and easier testing, while @Primary marks a default bean and @Qualifier specifies which bean to inject.

Uploaded by

gopal6291441556
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Spring Boot Auto-Wiring Notes

Introduction to @Autowired
@Autowired is a Spring annotation used for automatic dependency injection. It allows Spring’s
Inversion of Control (IoC) container to automatically resolve and inject collaborating beans into your
application without manual instantiation using the new keyword.

Key Benefits:

• Reduces boilerplate code.


• Promotes loose coupling between components.
• Enhances readability and maintainability.

Types of Dependency Injection with @Autowired

1. Field Injection

@Autowired
private SomeService someService;

• Injects the dependency directly into the field.


• Not recommended for unit testing due to lack of immutability and testability.

2. Constructor Injection (Preferred)

private final SomeService someService;

@Autowired
public MyComponent(SomeService someService) {
[Link] = someService;
}

• Preferred method.
• Ensures mandatory dependencies are provided.
• Supports immutability with final fields.
• Easier to test.

1
3. Setter Injection

private SomeService someService;

@Autowired
public void setSomeService(SomeService someService) {
[Link] = someService;
}

• Useful for optional dependencies.

Handling Multiple Beans of the Same Type


When multiple beans of the same type exist, ambiguity can arise. Spring provides two annotations to
resolve it:

@Primary
Marks a bean as the default choice for autowiring when multiple beans of the same type are available.

@Service
@Primary
public class CreditCardPayment implements PaymentService {
public String processPayment() {
return "Credit Card Payment";
}
}

• Chosen automatically if no @Qualifier is specified.

@Qualifier
Specifies exactly which bean to inject when multiple candidates exist.

@Service("payPalPayment")
public class PayPalPayment implements PaymentService {
public String processPayment() {
return "PayPal Payment";
}
}

@Autowired

2
public PaymentProcessor(@Qualifier("payPalPayment") PaymentService
paymentService) {
[Link] = paymentService;
}

• Overrides @Primary .
• Provides explicit bean selection.

Practical Example

Interface:

public interface PaymentService {


String processPayment();
}

Implementations:

@Service("creditCardPayment")
@Primary
public class CreditCardPayment implements PaymentService {
public String processPayment() {
return "Processed via Credit Card";
}
}

@Service("payPalPayment")
public class PayPalPayment implements PaymentService {
public String processPayment() {
return "Processed via PayPal";
}
}

Consumer Class:

@Component
public class PaymentProcessor {
private final PaymentService defaultService;
private final PaymentService specificService;

@Autowired
public PaymentProcessor(PaymentService defaultService,

3
@Qualifier("payPalPayment") PaymentService
specificService) {
[Link] = defaultService; // Will use @Primary bean
[Link] = specificService; // Will use @Qualifier
}

public void execute() {


[Link]([Link]());
[Link]([Link]());
}
}

Common Error
• ``: Occurs if multiple beans of the same type exist and no @Primary or @Qualifier is used.

Important Interview Questions with Answers

1. What is @Autowired in Spring?

@Autowired is an annotation used by Spring for automatic dependency injection. It allows Spring to
resolve and inject collaborating beans automatically without requiring manual instantiation.

2. What are the different ways to perform dependency injection in Spring?

• Constructor Injection: Recommended for required dependencies and immutability.


• Setter Injection: Best for optional dependencies.
• Field Injection: Simple but less testable and not recommended for complex applications.

3. Why is constructor injection preferred over field injection?

• Ensures mandatory dependencies are not missed.


• Supports immutability by allowing final fields.
• Makes unit testing easier.
• Promotes better design and cleaner code.

4. What is the use of @Primary in Spring Boot?

@Primary is used to mark a bean as the default choice when multiple beans of the same type are
available. If no @Qualifier is used, Spring injects the @Primary bean.

4
5. How does @Qualifier override @Primary ?

Even if a bean is marked as @Primary , if @Qualifier is used with another bean’s name at the injection
point, that explicitly specified bean will be injected instead. @Qualifier always takes precedence.

6. What happens if multiple beans are present without @Primary or @Qualifier ?

Spring throws a NoUniqueBeanDefinitionException because it cannot determine which bean to inject


among the available candidates.

7. Can we use @Autowired on private fields? Is it good practice?

Yes, Spring can inject dependencies into private fields using reflection. However, this approach is
discouraged in favor of constructor injection due to testability and clarity concerns.

8. Is @Autowired required in Spring Boot 3.x when there's only one constructor?

No. From Spring 4.3 onwards (including Spring Boot 3.x), if a class has only one constructor, Spring will
automatically use it for dependency injection even if @Autowired is not explicitly specified.

Summary

Annotation Purpose Scope of Use Notes

Automatic dependency Fields, constructors, Avoids manual new


@Autowired
injection setters keyword

Sets a default bean when Used unless @Qualifier


@Primary On a bean class
multiple exist is specified

Selects specific bean by


@Qualifier Injection point Overrides @Primary
name

Conclusion
Use @Autowired for efficient dependency management. Prefer constructor injection for better design
and testability. When dealing with multiple beans of the same type, use @Primary or @Qualifier to
resolve ambiguity effectively.

You might also like