Sobes.tech
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:

  1. Constructor Injection — dependencies are passed through constructor parameters. This ensures immutability of dependencies and ease of testing.

  2. 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.

  3. Field Injection — dependencies are injected directly into class fields using annotations (e.g., @Autowired in 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;
    }
}
What methods are used to implement dependency… - sobes.tech