0
0
Spring Bootframework~10 mins

Field injection and why to avoid it in Spring Boot - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to inject a dependency using field injection.

Spring Boot
public class UserService {
    @Autowired
    private [1] userRepository;
}
Drag options to blanks, or click blank then click option'
AAutowired
BuserRepository
CUserService
DUserRepository
Attempts:
3 left
💡 Hint
Common Mistakes
Using the variable name instead of the type.
Using the class itself instead of the dependency type.
2fill in blank
medium

Complete the code to inject a dependency using constructor injection instead of field injection.

Spring Boot
public class UserService {
    private final UserRepository userRepository;

    public UserService([1] userRepository) {
        this.userRepository = userRepository;
    }
}
Drag options to blanks, or click blank then click option'
AUserService
BUserRepository
CAutowired
DService
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name of the service instead of the dependency.
Forgetting to mark the constructor with @Autowired (optional in Spring Boot).
3fill in blank
hard

Fix the error in this field injection example by choosing the correct annotation to avoid issues.

Spring Boot
public class UserService {
    [1]
    private UserRepository userRepository;
}
Drag options to blanks, or click blank then click option'
A@Component
B@Inject
C@Autowired
D@Service
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Component or @Service on fields instead of classes.
Using @Inject without proper configuration.
4fill in blank
hard

Fill both blanks to rewrite field injection as constructor injection to improve testability and immutability.

Spring Boot
public class UserService {
    private final UserRepository userRepository;

    public UserService([1] userRepository) {
        this.userRepository = [2];
    }
}
Drag options to blanks, or click blank then click option'
AUserRepository
Bthis.userRepository
CuserRepository
DUserService
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the field to itself instead of the parameter.
Using wrong parameter type.
5fill in blank
hard

Fill all three blanks to create a Spring component with constructor injection and avoid field injection pitfalls.

Spring Boot
@[1]
public class OrderService {
    private final OrderRepository orderRepository;

    public OrderService([2] orderRepository) {
        this.orderRepository = [3];
    }
}
Drag options to blanks, or click blank then click option'
AService
BOrderRepository
CorderRepository
DComponent
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Component instead of @Service for service classes.
Mixing up parameter and field names in assignment.