Bird
0
0

What is wrong with the following Spring Boot code snippet?

medium📝 Debug Q14 of 15
Spring Boot - Inversion of Control and Dependency Injection
What is wrong with the following Spring Boot code snippet?
@Service
public class UserService {
    private Repository repo;

    @Autowired
    public void setRepo(Repository repo) {
        this.repo = repo;
    }
}

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    public void doSomething() {
        userService.repo.save();
    }
}
AField 'repo' in UserService is private and cannot be accessed directly
BMissing @Autowired on UserService constructor
CUserController should not use @Autowired on fields
DRepository interface is not annotated with @Service
Step-by-Step Solution
Solution:
  1. Step 1: Check access to 'repo' field and identify cause of error

    The 'repo' field in UserService is private and cannot be accessed directly from UserController. Calling userService.repo.save() causes a compilation error due to private access.
  2. Final Answer:

    Field 'repo' in UserService is private and cannot be accessed directly -> Option A
  3. Quick Check:

    Private fields can't be accessed outside class [OK]
Quick Trick: Private fields need getters; direct access causes error [OK]
Common Mistakes:
  • Assuming @Autowired must be on constructor only
  • Thinking field injection is disallowed in UserController
  • Confusing Repository annotation requirements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes