解决-Spring boot: 加载jar包外部json配置文件时,报错"File not found"

本文介绍了当Spring Boot应用打包后,如何处理activity-config.json配置文件不在jar包内的情况。通过手动分离配置文件到jar同级目录,并提供了一种非注解方式读取json内容的方法,包括在指定目录创建json文件、打包时分离配置文件及程序中读取配置文件内容的步骤。

描述

打包时把resource/activity-config.json文件分离到jar包同级目录下config/activity-config.json后,通过@Value("classpath:activity-config.json") private Resource activityConfigRes;方式,获取不到json里面的内容。

解决办法:不用注解,改用System.getProperty("user.dir") + "/config/activity-config.json";这种方式读取配置文件中的内容。

            String filePath = System.getProperty("user.dir")
                    + "/config/activity-config.json";
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            String areaData =  IOUtils.toString(in, Charset.forName("UTF-8"));
            ObjectMapper mapper = new ObjectMapper();
            ActivityConfig config = mapper.readValue(areaData, ActivityConfig.class);

如何加载jar包外部json配置文件实现步骤

第一步

resource目录下创建json配置文件activity-config.json
在这里插入图片描述

第二步

打包时从jar包中分离出配置文件到与jar包同级的文件夹config下。

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <!--跳过测试-->
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <!--指定启动类-->
                            <mainClass>**.**.Application</mainClass>
                        </manifest>
                    </archive>
                    <!--指定classes目录-->
                    <!--<classesDirectory>src/main/java</classesDirectory>-->
                    <outputDirectory>${project.package.directory}/${project.artifactId}</outputDirectory>
                    <!--排除classes目录下不需要打包的文件-->
                    <excludes>
                        <!--<exclude>META-INF/**</exclude>-->
                        <exclude>application.properties</exclude>
                        <exclude>*.json</exclude>  
                        <exclude>logback-spring.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <includeScope>compile</includeScope>
                            <!--复制依赖jar到指令目录-->
                            <outputDirectory>${project.package.directory}/${project.artifactId}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>

            </plugin>
            <!--复制资源文件到指定目录-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.package.directory}/${project.artifactId}/config/</outputDirectory>
                            <resources>
                                <resource>
                                    <!--资源文件的目录-->
                                    <directory>src/main/resources/</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

第三步

读取配置文件内容,转换成对象

        try {
            String filePath = System.getProperty("user.dir")
                    + "/config/activity-config.json";
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            String areaData =  IOUtils.toString(in, Charset.forName("UTF-8"));
            logger.info("读取活动配置文件:" + areaData);
            ObjectMapper mapper = new ObjectMapper();
            ActivityConfig config = mapper.readValue(areaData, ActivityConfig.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

如果要用到IOUtils,需要在pom文件中导入下面的配置。

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
我设置了,但是: Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1f1c9184] 2025-10-14T08:59:57.035+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-2] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/yaml] 2025-10-14T08:59:57.035+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-2] m.m.a.RequestResponseBodyMethodProcessor : Writing [ActionResult(code=200, msg=Success, data=PageListVO(list=[{flowTaskId=746639618119580037, unitName=t (truncated)...] 2025-10-14T08:59:57.036+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-2] o.s.web.servlet.DispatcherServlet : Completed 200 OK 2025-10-14T09:00:05.739+08:00 INFO 31008 --- [jnpf-boot] [io-30000-exec-5] jnpf.filter.AuthFilter : 请求路径: /api/rcm/BizBaseUnit/unit/TemplateDownload 2025-10-14T09:00:05.761+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-5] o.s.web.servlet.DispatcherServlet : GET "/api/rcm/BizBaseUnit/unit/TemplateDownload?menuId=707924726416147141&_t=1760403605735", parameters={masked} 2025-10-14T09:00:05.765+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [URL [file:/]] 2025-10-14T09:00:05.766+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-5] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found 2025-10-14T09:00:05.769+08:00 DEBUG 31008 --- [jnpf-boot] [io-30000-exec-5] .m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler jnpf.exception.ResultException#exception(ServletException) 2025-10-14T09:00:05.769+08:00 ERROR 31008 --- [jnpf-boot] [io-30000-exec-5] jnpf.exception.ResultException : 系统异常:No static resource api/rcm/BizBaseUnit/unit/TemplateDownload. org.springframework.web.servlet.resource.NoResourceFoundException: No static resource api/rcm/BizBaseUnit/unit/TemplateDownload. at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:585)。我这个是打成jar运行,jar就在我本地的win系统上。和我的开发环境一样。但是直接在idea中运行没问题,这个就报错
最新发布
10-15
C:\Users\Administrator\.jdks\ms-17.0.15\bin\java.exe -XX:TieredStopAtLevel=1 -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-Dmanagement.endpoints.jmx.exposure.include=*" "-javaagent:C:\Users\Administrator\AppData\Local\Programs\IntelliJ IDEA Ultimate 2025.1.3\lib\idea_rt.jar=56082" -Dfile.encoding=UTF-8 -classpath C:\Users\Administrator\IdeaProjects\demo1\target\classes;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-jdbc\2.6.13\spring-boot-starter-jdbc-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter\2.6.13\spring-boot-starter-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot\2.6.13\spring-boot-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-autoconfigure\2.6.13\spring-boot-autoconfigure-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-logging\2.6.13\spring-boot-starter-logging-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;D:\apache-maven-3.9.10\maven-repository\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\logging\log4j\log4j-to-slf4j\2.17.2\log4j-to-slf4j-2.17.2.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\logging\log4j\log4j-api\2.17.2\log4j-api-2.17.2.jar;D:\apache-maven-3.9.10\maven-repository\org\slf4j\jul-to-slf4j\1.7.36\jul-to-slf4j-1.7.36.jar;D:\apache-maven-3.9.10\maven-repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\apache-maven-3.9.10\maven-repository\org\yaml\snakeyaml\1.29\snakeyaml-1.29.jar;D:\apache-maven-3.9.10\maven-repository\com\zaxxer\HikariCP\4.0.3\HikariCP-4.0.3.jar;D:\apache-maven-3.9.10\maven-repository\org\slf4j\slf4j-api\1.7.36\slf4j-api-1.7.36.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-jdbc\5.3.23\spring-jdbc-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-beans\5.3.23\spring-beans-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-tx\5.3.23\spring-tx-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-web\2.6.13\spring-boot-starter-web-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-json\2.6.13\spring-boot-starter-json-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\core\jackson-databind\2.13.4.2\jackson-databind-2.13.4.2.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\core\jackson-annotations\2.13.4\jackson-annotations-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\core\jackson-core\2.13.4\jackson-core-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.13.4\jackson-datatype-jdk8-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.13.4\jackson-datatype-jsr310-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.13.4\jackson-module-parameter-names-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-tomcat\2.6.13\spring-boot-starter-tomcat-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.68\tomcat-embed-core-9.0.68.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.68\tomcat-embed-el-9.0.68.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.68\tomcat-embed-websocket-9.0.68.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-web\5.3.23\spring-web-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-webmvc\5.3.23\spring-webmvc-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-aop\5.3.23\spring-aop-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-context\5.3.23\spring-context-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-expression\5.3.23\spring-expression-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\spring\boot\mybatis-spring-boot-starter\2.2.2\mybatis-spring-boot-starter-2.2.2.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\2.2.2\mybatis-spring-boot-autoconfigure-2.2.2.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\mybatis\3.5.9\mybatis-3.5.9.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\mybatis-spring\2.0.7\mybatis-spring-2.0.7.jar;D:\apache-maven-3.9.10\maven-repository\com\h2database\h2\1.4.200\h2-1.4.200.jar;D:\apache-maven-3.9.10\maven-repository\com\mysql\mysql-connector-j\8.0.31\mysql-connector-j-8.0.31.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-core\5.3.23\spring-core-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-jcl\5.3.23\spring-jcl-5.3.23.jar com.example.demo.Demo1Application . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.13) 2025-07-11 15:39:15.048 INFO 14076 --- [ main] com.example.demo.Demo1Application : Starting Demo1Application using Java 17.0.15 on 闫晓强 with PID 14076 (C:\Users\Administrator\IdeaProjects\demo1\target\classes started by Administrator in C:\Users\Administrator\IdeaProjects\demo1) 2025-07-11 15:39:15.050 INFO 14076 --- [ main] com.example.demo.Demo1Application : No active profile set, falling back to 1 default profile: "default" 2025-07-11 15:39:15.553 WARN 14076 --- [ main] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.example.demo]' package. Please check your configuration. 2025-07-11 15:39:15.856 INFO 14076 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2025-07-11 15:39:15.865 INFO 14076 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2025-07-11 15:39:15.866 INFO 14076 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68] 2025-07-11 15:39:15.951 INFO 14076 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2025-07-11 15:39:15.951 INFO 14076 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 857 ms 2025-07-11 15:39:15.972 INFO 14076 --- [ main] com.zaxxer.hikari.HikariDataSource : defaultDataSource - Starting... 2025-07-11 15:39:16.111 INFO 14076 --- [ main] com.zaxxer.hikari.HikariDataSource : defaultDataSource - Start completed. 2025-07-11 15:39:16.118 INFO 14076 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:file:~/test' 2025-07-11 15:39:16.291 INFO 14076 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html] 2025-07-11 15:39:16.330 WARN 14076 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scriptDataSourceInitializer' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceInitializationConfiguration$SharedCredentialsDataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: No schema scripts found at location 'classpath:schema.sql' 2025-07-11 15:39:16.330 INFO 14076 --- [ main] com.zaxxer.hikari.HikariDataSource : defaultDataSource - Shutdown initiated... 2025-07-11 15:39:16.336 INFO 14076 --- [ main] com.zaxxer.hikari.HikariDataSource : defaultDataSource - Shutdown completed. 2025-07-11 15:39:16.338 INFO 14076 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2025-07-11 15:39:16.345 INFO 14076 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2025-07-11 15:39:16.360 ERROR 14076 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scriptDataSourceInitializer' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceInitializationConfiguration$SharedCredentialsDataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: No schema scripts found at location 'classpath:schema.sql' at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:745) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:420) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.6.13.jar:2.6.13] at com.example.demo.Demo1Application.main(Demo1Application.java:10) ~[classes/:na] Caused by: java.lang.IllegalStateException: No schema scripts found at location 'classpath:schema.sql' at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.getScripts(AbstractScriptDatabaseInitializer.java:128) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.applyScripts(AbstractScriptDatabaseInitializer.java:105) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.applySchemaScripts(AbstractScriptDatabaseInitializer.java:97) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.initializeDatabase(AbstractScriptDatabaseInitializer.java:75) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.afterPropertiesSet(AbstractScriptDatabaseInitializer.java:65) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.23.jar:5.3.23] ... 16 common frames omitted 进程已结束,退出代码为 1 请解释是什么意思并给出解决方法
07-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值