本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
转载自夜明的孤行灯
本文链接地址: https://www.huangyunkun.com/2016/01/21/spring-boot-with-webjars/
一个Java Web项目或多或少需要是一些javascript或者css依赖,比较容易想到的办法就是用前端构建工具管理依赖,然后直接拷贝到Webapp目录,当然spring boot对于静态资源还支持一下几个位置:
"classpath:/META-INF/resources/" "classpath:/resources/" "classpath:/static/" "classpath:/public/"
我对于前端管理工具并不喜欢,也不想安装诸如node等相关环境,这个时候就可以试用WebJars了。
WebJars
WebJars将前端资源打包到jar中,这样开发人员就可以简单的管理依赖,并且可以使用已有的JVM base构建工具和生态链,同时对于RequireJS也有一些自动化支持。
在Spring Boot中使用WebJars是非常简单的,简单的引入依赖就可以,所有资源都暴露在 /webjars/** 下,只要你知道版本号和文件名,就可以直接在前端页面中引用相关资源。
Spring Boot的支持
在Spring Boot中使用WebJars如此简单,主要是因为Spring Boot有一个默认的支持,是否启动对应配置的条件在OnEnabledResourceChainCondition类
class OnEnabledResourceChainCondition extends SpringBootCondition { public static final String WEBJAR_ASSERT_LOCATOR = "org.webjars.WebJarAssetLocator"; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConfigurableEnvironment environment = (ConfigurableEnvironment) context .getEnvironment(); ResourceProperties properties = new ResourceProperties(); RelaxedDataBinder binder = new RelaxedDataBinder(properties, "spring.resources"); binder.bind(new PropertySourcesPropertyValues(environment.getPropertySources())); Boolean match = properties.getChain().getEnabled(); if (match == null) { boolean webJarsLocatorPresent = ClassUtils.isPresent( WEBJAR_ASSERT_LOCATOR, getClass().getClassLoader()); return new ConditionOutcome(webJarsLocatorPresent, "Webjars locator (" + WEBJAR_ASSERT_LOCATOR + ") is " + (webJarsLocatorPresent ? "present" : "absent")); } return new ConditionOutcome(match, "Resource chain is " + (match ? "enabled" : "disabled")); } }
WebJarAssetLocator是WebJars中的类,如果当前classpath包含这个类,那么就启用对应配置。
而具体的配置和路径注册是在WebMvcAutoConfiguration类中,如果对应条件满足,且没有显式关闭它,那么就会注册一个
if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(cachePeriod)); }
当然,如果你自己注册了一个 /webjars/** 的处理器,Spring Boot并不会用默认的配置覆盖它。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
转载自夜明的孤行灯
本文链接地址: https://www.huangyunkun.com/2016/01/21/spring-boot-with-webjars/