开发一个SPringBoot博客项目,不想将一些个人信息写死在页面,想通过在配置文件读取方式展示到页面
将配置文件中的内容添加到thymeleaf的全局变量中,需要展示的时候可以直接在变量中读取
代码实现
1 新增配置文件
blog:
# 博客名称
name: 我的博客
logo: https://cdn.jsdelivr.net/gh/wangmx996/wangmx996.github.io/favicon.png
# 博主信息
blogerInfo:
qq: qq123456
csdn: 123456
2 重写configureViewResolvers方法
@Component
@ConfigurationProperties(prefix = com.xiao.blog.config.BlogConfig.PREFIX)
@Data
public class BlogConfig implements WebMvcConfigurer {
public static final String PREFIX = "blog";
@Resource(name="thymeleafViewResolver")
private ThymeleafViewResolver thymeleafViewResolver;
//博客名称
private String name;
private String logo;
private Map blogerInfo;
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
if (thymeleafViewResolver != null) {
Map<String, Object> vars = new HashMap<>(1);
vars.put("name", getName());
vars.put("logo", getLogo());
vars.put("blogerInfo", getBlogerInfo());
thymeleafViewResolver.setStaticVariables(vars);
}
WebMvcConfigurer.super.configureViewResolvers(registry);
}
}
页面中使用
<div th:text="${name}"></div>
<img th:src="${logo}"></img>
<div th:text="${blogerInfo}"></div>
展示效果如下