SpringFrameworkAutowiring
Spring Autowiring using @Autowired Annotation
Introduction
- Wiring: Process of defining object dependencies so that Spring can auto-inject the dependent objects into the target bean.
- Types of Wiring:
- Manual Wiring: Explicitly specifying dependencies in configuration files.
- Autowiring: Letting Spring handle dependency injection automatically.
Autowiring in Spring
- Autowiring in Spring allows automatic dependency injection using the @Autowired annotation.
- Spring container automatically resolves the dependencies and injects them into the appropriate beans.
Example Use-Case for Field Injection
Below is an example where a Student
class has a dependency on a Department
class. We use the @Autowired annotation to inject the Department
dependency automatically.
Student.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Student {
@Autowired
private Department department;
public void show() {
System.out.println(department.getDeptName());
}
}
Department.java
import org.springframework.stereotype.Component;
@Component
public class Department {
public String getDeptName() {
return "Computer Science";
}
}
Main Class
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Student student = context.getBean(Student.class);
student.show();
}
}
Configuration Class
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.example")
public class AppConfig {
}
Other Ways to Autowire Components
Spring provides different ways to perform autowiring:
-
By Type (Field Injection)
- Uses @Autowired on a class field.
- No need for setter methods.
- Example:
@Autowired private Department department;
-
By Constructor
- Uses @Autowired on the constructor.
- Best practice when working with immutable dependencies.
- Example:
@Autowired public Student(Department department) { this.department = department; }
-
By Setter Method
- Uses @Autowired on the setter method.
- Example:
@Autowired public void setDepartment(Department department) { this.department = department; }
Conclusion
- @Autowired simplifies dependency injection in Spring.
- It supports Field Injection, Constructor Injection, and Setter Injection.
- Helps reduce boilerplate code and improves manageability.
- Works with Component Scanning and Annotation-based Configuration.
Comments
Post a Comment