您是正确的,index.html 需要返回给 Spring 未知的端点。然后安排 Angular 应用管理未知路由。
我使用WebMvcConfigurerAdapter 处理这种情况。还将静态内容文件类型放在这里。
添加一个config 目录并在其中添加一个Java 文件WebMvcConfig(例如),其中包含以下内容:
package com.yourdomain.yourapp.config;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.resource.PathResourceResolver;
import java.io.IOException;
import javax.inject.Inject;
@Configuration
@EnableConfigurationProperties({ ResourceProperties.class })
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Inject
private ResourceProperties resourceProperties = new ResourceProperties();
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
Integer cachePeriod = resourceProperties.getCachePeriod();
final String[] staticLocations = resourceProperties.getStaticLocations();
final String[] indexLocations = new String[staticLocations.length];
for (int i = 0; i < staticLocations.length; i++) {
indexLocations[i] = staticLocations[i] + "index.html";
}
registry.addResourceHandler(
"/**/*.css",
"/**/*.html",
"/**/*.js",
"/**/*.json",
"/**/*.bmp",
"/**/*.jpeg",
"/**/*.jpg",
"/**/*.gif",
"/**/*.ico",
"/**/*.png",
"/**/*.ttf",
"/**/*.wav",
"/**/*.mp3",
"/**/*.eot",
"/**/*.svg",
"/**/*.woff",
"/**/*.woff2",
"/**/*.map"
)
.addResourceLocations(staticLocations)
.setCachePeriod(cachePeriod);
registry.addResourceHandler("/**")
.addResourceLocations(indexLocations)
.setCachePeriod(cachePeriod)
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
return location.exists() && location.isReadable() ? location : null;
}
});
}
}
我认为您还必须为组件扫描指定配置包。不妨先试试看是否可行。
@SpringBootApplication
@ComponentScan( basePackages = { "com.yourdomain.yourapp.config" })
public class SpringBoot extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBoot.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBoot.class, args);
}
}
如果您缺少依赖项。这就是我在build.gradle 中的内容:
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'javax.inject', name: 'javax.inject', version: '1'
optional group: 'org.springframework.boot', name: 'spring-boot-configuration-processor'
providedRuntime group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
}
希望这会有所帮助:-)