com.github.timo_reymann.vue_starter.configuration.WebConfiguration Maven / Gradle / Ivy
package com.github.timo_reymann.vue_starter.configuration;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import java.io.IOException;
@Configuration
@ConditionalOnProperty(prefix = "vue",name = "router-mode")
@Log
public class WebConfiguration implements WebMvcConfigurer {
public static final int TEN_MINUTES = 60 * 10 * 1_000;
@Autowired
private VueConfig vueConfig;
/**
* Add handlers to serve static resources such as images, js, and, css
* files from specific locations under web application root, the classpath,
* and others.
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("Applying resources handler cause router mode is set");
registry
.addResourceHandler(
"/**/*.css",
"/**/*.html",
"/**/*.js",
"/**/*.jsx",
"/**/*.png",
"/**/*.ttf",
"/**/*.woff",
"/**/*.woff2"
)
.setCachePeriod(TEN_MINUTES)
.addResourceLocations("classpath:/static/");
if (vueConfig.getRouterMode() == RouterMode.History) {
log.info("Set vue router mode to history and redirect not found to index.html");
registry.addResourceHandler("/", "/**")
.setCachePeriod(0)
.addResourceLocations("classpath:/static/index.html")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
return location.exists() && location.isReadable() ? location : null;
}
});
}
}
}