Sobes.tech
Junior — Middle

What are the consequences of using the @Autowired annotation in Spring?

sobes.tech AI

Answer from AI

The @Autowired annotation in Spring is used for automatic dependency injection. When used, Spring automatically searches for and injects a suitable bean into a field, constructor, or setter.

Consequences of using @Autowired:

  • Automation of dependency injection: reduces boilerplate code, simplifying configuration.
  • Dependence on Spring context: the object must be managed by Spring (e.g., a component or service).
  • Possible errors when no suitable bean is found: if no matching bean is found, an exception NoSuchBeanDefinitionException will be thrown by default. To avoid this, you can use @Autowired(required = false).
  • Implicit dependencies: sometimes it is difficult to immediately understand which dependencies are injected, which can complicate maintenance.

Example:

@Component
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // userRepository will be automatically injected by Spring
}