【问题标题】:angular2 spring-boot project structureangular2 spring-boot项目结构
【发布时间】:2017-02-18 04:22:21
【问题描述】:

我有一个新的 angular2 项目,它是使用快速入门中描述的标准文件结构构建的。我正在尝试构建一个 API 网关并让 spring-boot 托管我的应用程序,但是我无法将 boot 配置为使用创建生成源的项目中的 /dist 目录。项目结构如下:

project  
|--dist  
|--node_modules
|--src  
|  |--app  
|  |--assets
|  |--main  
|  |  |--java  
|  |  |--resources
|  |  |  |--config  
|  |  |--webapp
|  |  |  |--WEB-INF  

我想使用默认的 /dist 目录,这样我仍然可以使用 npm/webpack 在 UI 上进行持续开发。

我尝试像这样配置静态资源目录:

 spring.resources.staticLocations: /dist

但这似乎不起作用。

我创建了一个资源处理程序来直接指向 dist 目录:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

  @Override
  public void addResourceHandlers(final ResourceHandlerRegistry registry) {

    String currentPath = new File("./").getAbsolutePath();
    currentPath = "file:///" + currentPath;

   registry.addResourceHandler("/**").addResourceLocations(currentPath + "/dist/");
  }
}  

这解决了部分问题,但现在我的根 URL ('/') 不再映射到 index.html。

是否有更简单/更好的方式来配置 spring-boot 以查找 /dist 项目目录?我的项目结构应该改变吗?我真的很想让所有这些部分干净利落地一起工作。

【问题讨论】:

  • 您需要使用类路径中的位置,而不是尝试直接在磁盘上点击它。 (毕竟它不会在 jar 中!)我通常将我的 JS 管道配置为输出到target/classes

标签: javascript java spring angular spring-boot


【解决方案1】:

Spring Boot 会自动添加静态 web 资源 位于以下任一目录中:

/META-INF/resources/

/resources/

/static/

/public/

文件夹相对于 src/main/resources

如果你像下面这样放置 index.html,那么 spring 可以为你的文件提供服务 无需任何配置。

src/main/resources/META-INF/resources/index.html

src/main/resources/resources/index.html

src/main/resources/static/index.html

src/main/resources/public/index.html

【讨论】:

    【解决方案2】:

    我接受了@chrylis 的建议,并将 webpack 构建的目标目录指向 build/dist(使用 Gradle)。

    我避免将生成的源代码放在 /resources/** 中,因为最终这将被构建到 .war 中并部署到企业应用程序服务器——我不希望我的构建中有很多包含/排除逻辑来支持这一点.此外,构建目录似乎更适合生成 .js 源代码。

    我的项目结构现在如下所示:

    project  
    |--build
    |  |--dist
    |  |--...  
    |--node_modules
    |--src  
    |  |--app  
    |  |--assets
    |  |--main  
    |  |  |--java  
    |  |  |--resources
    |  |  |  |--config  
    |  |  |--webapp
    |  |  |  |--WEB-INF  
    

    我消除了 WebMvcConfigurerAdapter 并将静态资源配置为指向我在构建中的 dist 目录:

    spring.resources.static-locations: "file:./build/dist/"  
    

    我现在能够运行 Webpack、Spring-Boot 或部署到我的应用程序服务器,使用相同的源和非常少的配置开销。

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 2019-06-23
      • 2017-06-11
      • 2021-05-29
      • 1970-01-01
      • 2018-04-26
      • 2018-07-13
      • 2017-04-15
      • 1970-01-01
      相关资源
      最近更新 更多