>我的项目需要从外部目录加载应用程序上下文 bean(它应该通过 Java 程序参数或"类路径"参数等进行管理(。这个想法是,用gradle创建的JAR不包含applicationContext.xml,因此可以在不重新构建JAR的情况下对其进行更新/替换。我的 Spring 引导应用程序类如下所示:
@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
首先检查你的类路径的实际外观。您可以通过以下方式做到这一点:
System.out.println(System.getProperty("java.class.path"));
并检查是否完整(或从您启动 java 命令的相对路径(到您的目录的路径是否存在。
如果没问题
在主类中而不是
SpringApplication.run(SampleApplication.class, args);
尝试
new SampleApplication().configure(new SpringApplicationBuilder(SampleApplication.class)).run(args);
使用 从外部目录加载应用程序上下文
@SpringBootApplication
@ImportResource({"file:/yourfullpath/applicationContext.xml"})
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}