Sobes.tech
Junior — Middle

What strategies for Bean implementation exist in Spring and how to determine the most suitable in a specific situation?

sobes.tech AI

Answer from AI

In Spring, there are several main strategies for bean injection:

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

  2. Setter Injection — dependencies are set via setter methods after the object is created. It allows changing dependencies after creation but can lead to an object state with incomplete dependencies.

  3. Field Injection — dependencies are injected directly into class fields using annotations (@Autowired). Convenient, but complicates testing and breaks encapsulation.

How to choose the appropriate strategy:

  • If the dependency is mandatory and must be set during object creation — prefer constructor injection.
  • If the dependency is optional or can change — setter injection is suitable.
  • Field injection is convenient for quick prototyping but not recommended for production code due to testing and maintenance issues.

Example of constructor injection:

@Component
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}
What strategies for Bean implementation exist in… - sobes.tech