springboot thymeleaf 后端 全局变量


springboot thymeleaf  后端 全局变量

pom.xml 中:


<dependency>
    <groupId>com.google.guavagroupId>
    <artifactId>guavaartifactId>
    <version>17.0version>
dependency>

任意Spring能扫到的有类中:

import org.springframework.core.env.Environment;

@Resource
    private Environment env;


@Resource
    private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
        if(viewResolver != null) {
            Map vars = Maps.newHashMap();
            vars.put("oauthServerIp", "http://127.0.0.1:9101");
            vars.put("oauth2Serverurl", env.getProperty("security.oauth2.serverurl"));
            viewResolver.setStaticVariables(vars);
        }
    }

application.properties

#自定义非官方配置
security.oauth2.serverurl=http://127.0.0.1:9191

html文件或任务layout的文件中:

<li><a th:href="@{''+${oauth2Serverurl}+'/cms'}" class="news">首页a>li>

js变量放到header.html中:

<script th:inline="javascript">
        const oauth2Serverurl= '[(${oauth2Serverurl})]';
        const oauthServerIp= '[(${oauthServerIp})]';
    script>

参考:

Spring Boot 中读取配置属性的几种方式:https://www.jianshu.com/p/2aadd10f655f

Maps.newHashMap()是个啥 https://blog.csdn.net/Ting1king/article/details/108994207

Spring Boot 中读取配置属性的几种方式