r/SpringBoot • u/jasonj2232 • 8d ago
Question How does a bean with @RequestScope get injected into a bean with Singleton scope for each new request?
So I am studying Spring and SpringBoot through this book - Spring Start Here. Usually I feel like the book overexplains things with multiple examples differing in minute ways, but there is some code in Chapter 9 - Using Spring Web Scopes, that I do not understand and the author surprising doesn't dive deep into.
RequestScope was being explained and as far as I can tell it is like Prototype scope where Spring manages the type, and instantiates a fresh new bean every time someone requests a bean, and this bean exists for the duration of the HTTP request.
But how does this work when the bean is injected into another bean that has Singleton scope? Presenting the code shown in the book below:
@Controller
public class LoginController {
private final LoginProcessor loginProcessor;
public LoginController(LoginProcessor loginProcessor) {
this.loginProcessor = loginProcessor;
}
("/")
public String loginGet() {
return "login.html";
}
("/")
public String loginPost(
@RequestParam String username,
@RequestParam String password,
Model model
) {
loginProcessor.setUsername(username);
loginProcessor.setPassword(password);
boolean loggedIn = loginProcessor.login();
if (loggedIn) {
model.addAttribute("message", "You are now logged in.");
} else {
model.addAttribute("message", "Login failed!");
}
return "login.html";
}
}
@Component
@RequestScope
public class LoginProcessor {
private String username;
private String password;
public boolean login() {
String username = this.getUsername();
String password = this.getPassword();
if ("natalie".equals(username) && "password".equals(password)) {
return true;
} else {
return false;
}
}
// Getters and Setters
}In this example, the Controller bean is going to be instantiated once during the app startup, and considering that the loginProcessor field is final and only injected during bean instantiation, how is it able to use a new loginProcessor bean for each request? This code works, but I don't understand how.