首页 > 解决方案 > FileNotFoundException:对于部署在 Tomcat 中的 Spring Boot 应用程序中的属性文件

问题描述

我有一个 Spring Boot 应用程序,它使用位于 src/main/config 中的属性文件中的一些参数。我需要在不同的环境中运行这个应用程序:DEV、SIT、PROD 等,并且我每次都需要更改该文件的属性。

我在类路径中,在 src/main/config 和 tomcat 文件夹中,在 instance-config 中有这个文件。当我在 Tomcat 上部署应用程序时,我需要它使用位于 tomcat 文件夹中的文件中的配置。

不过,我有一个问题:它找不到我的属性文件。

我试图创建一些配置文件,以便仅在“dev”上使用类路径(src/main/config)中的属性文件,但我无法完成构建,因为它给了我错误:“无法解析配置类 [com. db.wmdl.config.TestConfig];嵌套异常为 java.io.FileNotFoundException:类路径资源 [wmdl_options_app.properties] 无法打开,因为它不存在”

我在 pom 中有这个配置文件部分:

<profiles>
        <profile>
            <id>dev</id>
            <build>
                <resources>
                    <resource>
                        <directory>${project.basedir}/src/main/config</directory>
                    </resource>
                    <resource>
                        <directory>${project.basedir}/src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
        <profile>
            <id>tomcat</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <packaging.type>war</packaging.type>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                    <version>2.2.4.RELEASE</version>
                    <scope>provided</scope>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

这是包含对属性文件的引用的类:

@SpringBootApplication( scanBasePackages = {"com.db.wmdl.glue2g.*","com.db.wmdl.fo.service","com.db.wmdl.fo.persistence", "com.db.wmdl.fo.serversync"})
@PropertySource("classpath:wmdl_options_app.properties")
@EnableScheduling
public class Application {

    @PostConstruct
    public void init() throws IOException {
        LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        context.setConfigLocation(new ClassPathResource("log4j-dl-fo-config.xml").getURI());
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

如何使我的应用程序工作并从 instance-config 文件夹中读取属性?

标签: javaspring-boottomcat

解决方案


如果您使用 tomcat 配置文件运行,您还需要将这些添加到 tomcat 配置文件中。

<build>
                <resources>
                    <resource>
                        <directory>${project.basedir}/src/main/config</directory>
                    </resource>
                    <resource>
                        <directory>${project.basedir}/src/main/resources</directory>
                    </resource>
                </resources>
            </build>

此外,默认情况下,tomcat 配置文件处于活动状态。您需要专门激活开发配置文件。


推荐阅读