【问题标题】:Spring Boot - loading applicationContext.xml from external directorySpring Boot - 从外部目录加载 applicationContext.xml
【发布时间】:2018-04-10 21:12:39
【问题描述】:

我的项目需要从外部目录加载应用程序上下文 bean(它应该通过 Java 程序参数或“类路径”参数等进行管理)。这个想法是使用 gradle 创建的 JAR 不包含 applicationContext.xml,因此可以在不重新构建 JAR 的情况下对其进行更新/替换。我的 Spring Boot 应用程序类如下所示:

@SpringBootApplication
@ImportResource({"classpath:applicationContext.xml"})
public class SampleApplication {

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

我的问题是如何实现这一目标?我试图将 -classpath 参数设置为目录位置,但它不起作用。我在应用程序启动时遇到异常(当我尝试执行 JAR 时):

java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist

【问题讨论】:

  • 对于初学者,我会说这是一个非常糟糕的主意,您不希望外部用户弄乱您的应用程序配置。他们可以很容易地破坏事物并相信我他们会的。话虽如此,Spring 参考指南有一整节关于loading resources。简而言之,不要使用classpath:,而只需使用file: 并指向xml 文件所在的位置。或者简单地使用一个占位符 (${app.config}) 并在启动应用程序时指定它。

标签: java spring spring-boot


【解决方案1】:

首先检查您的类路径的实际外观。 你可以这样做:

System.out.println(System.getProperty("java.class.path"));

检查是否完整(或从您开始 java 命令的相对路径)到您的目录的路径是否存在。

如果没问题

在主类而不是

SpringApplication.run(SampleApplication.class, args);

试试

new SampleApplication().configure(new SpringApplicationBuilder(SampleApplication.class)).run(args);

【讨论】:

    【解决方案2】:

    使用从外部目录加载应用程序上下文

    @SpringBootApplication
    @ImportResource({"file:/yourfullpath/applicationContext.xml"})
    public class SampleApplication {
    
       public static void main(String[] args) {
          SpringApplication.run(SampleApplication.class, args);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 1970-01-01
      • 2018-12-19
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 2017-05-11
      相关资源
      最近更新 更多