Field Injection in Spring: What It Is and How It Works
@Autowired annotation. It lets Spring set the required objects without needing explicit constructor or setter methods.How It Works
Field injection works by letting Spring automatically fill in the needed objects directly into the fields of a class. Imagine you have a toolbox and you want to use a hammer inside your workbench. Instead of you going to get the hammer yourself, Spring acts like a helper who places the hammer right inside your workbench drawer for you.
When Spring creates an object, it looks for fields marked with @Autowired and then finds the matching objects from its container to put into those fields. This happens behind the scenes, so you don't have to write code to pass those objects around.
This makes your code simpler because you just declare what you need, and Spring takes care of providing it.
Example
This example shows a service class that needs a repository. The repository is injected directly into the field using @Autowired.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component class UserRepository { public String getUser() { return "User1"; } } @Component class UserService { @Autowired private UserRepository userRepository; public void printUser() { System.out.println(userRepository.getUser()); } } import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("your.package.name"); UserService userService = context.getBean(UserService.class); userService.printUser(); context.close(); } }
When to Use
Field injection is useful when you want quick and simple dependency setup without writing constructors or setters. It is handy in small projects or prototypes where you want to reduce boilerplate code.
However, for larger projects or when you want better testability and clearer dependencies, constructor injection is often preferred. Field injection can make it harder to see what dependencies a class needs and can complicate unit testing.
Use field injection when you want simplicity and your project is small or when you are working with legacy code that already uses it.
Key Points
- Field injection uses
@Autowiredon fields to inject dependencies automatically. - It simplifies code by removing the need for constructors or setters.
- It can make testing and understanding dependencies harder.
- Best for small projects or quick setups, but constructor injection is better for larger, maintainable codebases.