根据Spring文档,如果Spring IOC容器可识别Web,则@ApplicationScope Beans可以作为ServletContext属性看到。
我知道我可以在百里香模板中使用${@beanName}
访问@ApplicationScope Bean,但是为什么不能在百里香文件显示中使用${#servletContext.getAttribute('myAttribute')}
访问@ApplicationScope Bean?
下面是我的代码段。
@SpringBootApplication
public class Application {
@Autowired
private BranchService branchService;
public static void main(String[] args) {
SpringApplication.run(RetailStoreApplication.class, args);
}
@ApplicationScope
@Bean(value = "branches")
public List<Branch> branches() {
return branchService.queryAllBranches();
}
}
@Controller
public class HomeController {
@GetMapping(value = { "/", "/home" })
public String home() {
return "home.html";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
Below are all the branch, please choose one for this branch.
<span th:if="${#servletContext.getAttribute('branches')} == null">NULL</span>
<ul th:each="branch : ${#servletContext.getAttribute('branches')}">
<li th:text="${branch.name}" />
</ul>
</body>
</html>
返回的“分支”结果为null。我正在将spring-boot2与web-starter和thymeleaf-starter一起使用。
已经尝试过this,但在我的情况下不起作用。
欢迎任何回复,谢谢!