首页 > 解决方案 > 如何设置 Spring/Gradle 项目类路径以获取配置 XML 文件

问题描述

我有一个简单的基于 Spring、Gradle 的 Web 服务项目,其结构如下:

UserSettingController
  src/main/java
    com.ui.usersetting.datamodel
    com.ui.usersetting.restinterface
    com.ui.usersetting.UserSettingController
  resources
    resources_deployment1
       spring-resource1.xml
    resources_deployment2
    ...

有一个 @Autowired JdbcTemplate 变量,com.ui.usersetting.datamodel 其定义出现在resource/resources_deployment1/spring-resource1.xml. @Configuration 文件中也com.ui.usersetting.datamodel包含 @ImportResource("classpath:spring-resource1.xml").

这可以构建和部署,但是当我点击 中定义的端点之一时 com.ui.usersetting.restinterface,我从 Spring 收到以下错误:

class path resource [spring-resource1.xml] cannot be opened because it does not exist

我假设这意味着UserSettingController/resources/resources_deployment1/包含spring-resource1.xml的 不会出现在类路径上。我试图通过在 Eclipse 中设置类路径来解决此问题,但由于我使用 Gradle 命令行命令而不是 Eclipse 构建,因此此修复不起作用。

我需要维护上面的结构,而不是移动spring-resource1.xmlsrc/main/resources,以与我们组中的其他项目保持一致。那么,我怎样才能让 Spring 在正确的地方寻找spring-resourc1.xml呢?

标签: spring-bootgradle

解决方案


只需将额外的resources文件夹添加到您的sourceSets. 假设您有例如 3 个resources_deployment文件夹:

sourceSets {
    main {
        resources {
            (1..3).each {
                srcDir "resources/resources_deployment$it"
            }
        }
    }
} 

推荐阅读