Junior — Middle
What methods are used to implement dependency injection into Bean objects?
sobes.tech AI
Answer from AI
Dependency Injection in Java Bean objects is usually implemented using the following methods:
-
Constructor Injection — dependencies are passed through constructor parameters. This ensures immutability of dependencies and ease of testing.
-
Setter Injection — dependencies are set via setter methods after object creation. It allows changing dependencies after creation but can lead to an object state with uninitialized dependencies.
-
Field Injection — dependencies are injected directly into class fields using annotations (e.g.,
@Autowiredin Spring). It is convenient but complicates testing and breaks encapsulation.
Example of constructor injection in Spring:
@Component
public class Service {
private final Repository repository;
@Autowired
public Service(Repository repository) {
this.repository = repository;
}
}