I am trying to understand how the Session scoped bean work and have tried the example from here.
HelloMessageGenerator.java
JavaScript
x
public class HelloMessageGenerator {
private String message;
public HelloMessageGenerator() {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
HelloMessageBean.java
JavaScript
@Configuration
public class HelloMessageBean {
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestScopedBean() {
System.out.println("bean created");
return new HelloMessageGenerator();
}
}
HelloMessageController.java
JavaScript
@Controller
public class HelloMessageController {
@Resource(name = "sessionScopedBean")
HelloMessageGenerator sessionScopedBean;
@RequestMapping("/scopes/session")
public String getSessionScopeMessage(final Model model) {
model.addAttribute("previousMessage", sessionScopedBean.getMessage());
sessionScopedBean.setMessage("Good afternoon!");
model.addAttribute("currentMessage", sessionScopedBean.getMessage());
return "scopesExample";
}
}
When I go to http://localhost:8080/scopes/session I get an error.
scopesExample.html
JavaScript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<p th:text="${previousMessage}">previous message</p>
<p th:text="${currentMessage}">current message</p>
</body>
</html>
The error I am getting is as if the mapping would not exist:
JavaScript
This application has no explicit mapping for /error, so you are seeing this as a fallback. There was an unexpected error (type=Not Found, status=404).
Advertisement
Answer
I was missing the thymeleaf dependency in the pom.
JavaScript
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
This is why I was getting a 404 when going to localhost:8080/scopes/request
After adding the thymeleaf dependency the bean scope was working as expected. For a session scope bean the bean is created only once per session or after the configured session timeout. For a request scope bean it is created for every request (ie. each time one hits the endpoint).