在Spring Boot 1.1.5和1.1.6中都有这个问题-我使用@Value注释加载类路径资源,当我从STS(3.6.0,Windows)中运行应用程序时,它工作得很好.但是,当我运行一个MVN包,然后try 运行JAR时,我得到了FileNotFound异常.

资源message.txt位于src/main/resources中.我判断了JAR,并验证它在顶层(与application.properties相同的层)包含文件"message.txt".

以下是应用程序:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Value("${message.file}")
    private Resource messageResource;

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

    @Override
    public void run(String... arg0) throws Exception {
        // both of these work when running as Spring boot app from STS, but
        // fail after mvn package, and then running as java -jar
        testResource(new ClassPathResource("message.txt"));
        testResource(this.messageResource);
    }

    private void testResource(Resource resource) {
        try {
            resource.getFile();
            logger.debug("Found the resource " + resource.getFilename());
        } catch (IOException ex) {
            logger.error(ex.toString());
        }
    }
}

例外情况:

c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble
m\target>java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-16 08:46:34.635  INFO 5976 --- [           main] demo.Application
                  : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo
der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo
-0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s
ts-3.5.1.RELEASE\classpath-resource-problem\target)
2014-09-16 08:46:34.640 DEBUG 5976 --- [           main] demo.Application
                  : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA
SE
2014-09-16 08:46:34.681  INFO 5976 --- [           main] s.c.a.AnnotationConfigA
pplicationContext : Refreshing org.springframework.context.annotation.Annotation
ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014];
root of context hierarchy
2014-09-16 08:46:35.196  INFO 5976 --- [           main] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2014-09-16 08:46:35.210 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.211 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.215  INFO 5976 --- [           main] demo.Application
                  : Started Application in 0.965 seconds (JVM running for 1.435)

2014-09-16 08:46:35.217  INFO 5976 --- [       Thread-2] s.c.a.AnnotationConfigA
pplicationContext : Closing org.springframework.context.annotation.AnnotationCon
figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo
t of context hierarchy
2014-09-16 08:46:35.218  INFO 5976 --- [       Thread-2] o.s.j.e.a.AnnotationMBe
anExporter        : Unregistering JMX-exposed beans on shutdown

推荐答案

resource.getFile()希望资源本身在文件系统上可用,即它不能嵌套在jar文件中.这就是为什么当您在STS(Spring工具套件)中运行应用程序时,它可以工作,但一旦您构建了应用程序并从可执行jar运行它,它就不工作了.我建议使用getInputStream()而不是getFile()来访问资源的内容.这将允许您阅读资源的内容,无论它位于何处.

Java相关问答推荐

在这种情况下我应该/可以使用Java抽象工厂(或工厂方法)吗?

我想知道为什么我的控制器给出嵌套响应

我们如何直接使用kerminldap服务票证来通过ldap进行身份验证并形成LDAP上下文

Annotation @ Memphier无法正常工作,并表示:class需要一个bean,但找到了2个bean:

JPackaged应用程序启动MSI调试,然后启动System. exit()

如何配置ActiveMQ Artemis以使用AMQP 1.0和其他协议与Java

解析Javadoc时链接的全限定类名

我需要生成一个文件来整合每个特性执行的所有JSON结果

Bean定义不是从Spring ApplationConext.xml文件加载的

如何使用带有谓词参数的方法,而不使用lambda表达式

在Java 17中使用两个十进制数字分析时间时出错,但在Java 8中成功

把一条整型短裤和两条短裤装成一条长的

如何在JavaFX中处理多个按钮

如何在构建Gradle项目时排除com.google.guava依赖项的一个变体

如果按钮符合某些期望,如何修改它的文本?

如何读取3个CSV文件并在控制台中按顺序显示?(Java)

如何在运行docker的应用程序中获取指定的配置文件

无限递归Java问题

Java递归泛型是否可以被视为继承和重写的语法糖

多线程、并发和睡眠未按预期工作