Complete the code to inject a dependency using field injection.
public class UserService { @Autowired private [1] userRepository; }
The field type must be the class or interface to inject, here UserRepository.
Complete the code to inject a dependency using constructor injection instead of field injection.
public class UserService { private final UserRepository userRepository; public UserService([1] userRepository) { this.userRepository = userRepository; } }
The constructor parameter type must match the dependency type UserRepository to be injected.
Fix the error in this field injection example by choosing the correct annotation to avoid issues.
public class UserService { [1] private UserRepository userRepository; }
@Autowired is the Spring annotation for field injection. Using it properly is required for Spring to inject the dependency.
Fill both blanks to rewrite field injection as constructor injection to improve testability and immutability.
public class UserService { private final UserRepository userRepository; public UserService([1] userRepository) { this.userRepository = [2]; } }
The constructor parameter type is UserRepository, and the assignment uses the parameter userRepository.
Fill all three blanks to create a Spring component with constructor injection and avoid field injection pitfalls.
@[1] public class OrderService { private final OrderRepository orderRepository; public OrderService([2] orderRepository) { this.orderRepository = [3]; } }
@Service marks the class as a Spring service component. The constructor parameter type is OrderRepository, and the assignment uses the parameter orderRepository.