Thymeleaf cannot get Spring @ApplicationScope Bean

Viewed 355

According to Spring document, @ApplicationScope Beans are visible as ServletContext attributes if Spring IOC container is web-aware.

I know i can access to @ApplicationScope Beans using ${@beanName} in thymeleaf template, but why can't I access to them using ${#servletContext.getAttribute('myAttribute')} as thymeleaf document show?

Below is my code snippet.

@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>

The returning 'branches' result is null. I'm using spring-boot2 with web-starter and thymeleaf-starter.

Have already try this, but not work in my case.

Any response is welcome, thanks!

0 Answers
Related