You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建多模块Spring MVC应用?依赖模块视图无法加载求助

解决CoreApplication视图无法被CustomerApplication识别的问题

嘿,这个问题我之前碰到过好多次啦!核心原因其实是Spring Boot对控制器Bean和视图资源的加载逻辑不一样——控制器能被识别,说明你的组件扫描配置是ok的(比如Core的控制器包刚好在Customer启动类的扫描范围内,或者你手动加了@ComponentScan包含Core的包),但视图文件(比如Thymeleaf、JSP这些)默认只会加载当前项目的资源目录,不会自动去依赖的Jar包里找。

下面给你几个实用的解决方案,按需选就行:

方案1:调整CoreApplication的资源目录结构

Spring Boot默认会自动加载Jar包中META-INF/resources/目录下的所有静态资源和模板文件。所以你可以直接修改CoreApplication的项目结构:

  • 把原来src/main/resources/templates/下的视图文件,移动到src/main/resources/META-INF/resources/templates/
  • 把静态资源(css、js、图片等)移到src/main/resources/META-INF/resources/static/

这样当CustomerApplication引入Core的Jar依赖后,Spring Boot就能自动发现这些视图资源了,不需要额外配置。

方案2:在CustomerApplication中配置资源加载路径

如果不想改动Core的项目结构,直接在CustomerApplication的配置文件里手动指定额外的资源扫描路径就行,关键是要用上classpath*:前缀(它表示扫描所有类路径,包括依赖Jar包):

用application.properties的写法:

# 如果是Thymeleaf模板,配置前缀为所有类路径下的templates目录
spring.thymeleaf.prefix=classpath*:/templates/
# 如果是JSP模板,调整对应的前缀和后缀
spring.mvc.view.prefix=/WEB-INF/templates/
spring.mvc.view.suffix=.jsp
# 静态资源同样添加classpath*:的路径
spring.web.resources.static-locations=classpath:/static/,classpath*:/static/

用application.yml的写法:

spring:
  thymeleaf:
    prefix: classpath*:/templates/
  web:
    resources:
      static-locations:
        - classpath:/static/
        - classpath*:/static/
  # 要是用JSP的话,加上这段配置
  mvc:
    view:
      prefix: /WEB-INF/templates/
      suffix: .jsp

方案3:自定义WebMvc配置(复杂场景适用)

如果上面两种方案都不满足你的需求,还可以写一个配置类,注册自定义的资源处理器:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CustomResourceConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 处理模板资源的访问路径
        registry.addResourceHandler("/templates/**")
                .addResourceLocations("classpath:/templates/", "classpath*:/templates/");
        // 处理静态资源的访问路径
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/", "classpath*:/static/");
    }
}

最后别忘了检查两点:

  • 确保CoreApplication打包时,视图和静态资源都被正确打包到Jar里了(Maven默认会把src/main/resources下的文件打包进去,只要路径正确就没问题)
  • 重启CustomerApplication,测试视图访问是否正常

内容的提问来源于stack exchange,提问作者Danka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:35:31