微服务现在最流行的莫过于springboot,官方推荐两种模板语言,freemarker和thymeleaf,本文只介绍thymeleaf中如何定义全局常量。百度一搜thymeleaf的全局常量定义,都是让把常量写在“message_*”文件中,当然,做国际化的时候这个没问题 ,可是随着现在微服务大行其道,有很多不是国际化的东西需要定义,例如服务A调用服务B,这时候肯定要在A中配置B的url,这时候再写入message明显不合适了。
惯例先上思路
在模板解析时候就将常量写入,重写模板解析配置方法。看springboot源码
publicabstractclassWebMvcConfigurerAdapterimplementsWebMvcConfigurer{
/**
* {@inheritDoc}
*
This implementation is empty.
*/
@Override
publicvoidconfigureViewResolvers(ViewResolverRegistryregistry){
}
}
目测应该是重写这货就可以了,talk is cheap,show me the code
动手重写
1.现在Application.properties中定义两个常量,用于文件上传和预览
upload.path=http://localhost:9091/accessory/upload
image.view.path=http://localhost:9091/accessory/open?id=
2.重写configureViewResolvers(ViewResolverRegistry registry)
@Resource(name="thymeleafViewResolver")
privateThymeleafViewResolverthymeleafViewResolver;
@Value("${upload.path}")
privateStringdefaultUploadPath;
@Value("${image.view.path}")
privateStringdefaultImageViewPath;
@Override
publicvoidconfigureViewResolvers(ViewResolverRegistryregistry){
if(thymeleafViewResolver!=null){
Mapvars=newHashMap<>(8);
vars.put("uploadPath",defaultUploadPath);
vars.put("defaultImageViewPath",defaultImageViewPath);
thymeleafViewResolver.setStaticVariables(vars);
}
super.configureViewResolvers(registry);
}
3.模板上使用 html中
js中 写法比较奇怪, //
/*
varbasePath='http://www.baidu.com';
varuploadPath=[[${uploadPath}]];
vardefaultImageViewPath=[[${defaultImageViewPath}]];
/*]]>*/
就是酱紫。
长按关注我吧 ^_^