Java 在Spring引导中配置文件位于jar文件之外
我有一个SpringBootCamel应用程序,其目录结构如下 我想把这个项目转换成一个jar文件。但是我希望在jar之外有3个文件,这样当配置发生变化时,我就不需要一次又一次地重新部署我的应用程序。 这3个文件是 应用程序属性 CamelContext.xml sql.properties 我可以灵活地硬编码文件位置的路径。有谁能帮我解决这个问题吗Java 在Spring引导中配置文件位于jar文件之外,java,spring,spring-boot,jar,apache-camel,Java,Spring,Spring Boot,Jar,Apache Camel,我有一个SpringBootCamel应用程序,其目录结构如下 我想把这个项目转换成一个jar文件。但是我希望在jar之外有3个文件,这样当配置发生变化时,我就不需要一次又一次地重新部署我的应用程序。 这3个文件是 应用程序属性 CamelContext.xml sql.properties 我可以灵活地硬编码文件位置的路径。有谁能帮我解决这个问题吗 既然我已经解决了这个问题,我将为任何试图实现同样目标的人发布解决方案 @SuppressWarnings("resource") public s
既然我已经解决了这个问题,我将为任何试图实现同样目标的人发布解决方案
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
/*To load CamelContext.xml file */
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomResourceLoader customResourceLoader = (CustomResourceLoader) context.getBean("customResourceLoader");
customResourceLoader.showResourceData();
/*To load the properties file*/
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(Application.class)
.properties("spring.config.name:application.properties,sql",
"spring.config.location=D:/external/application.properties,D:/external/sql.properties")
.build().run(args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
}
在与主类相同的包中创建CustomResourceLoader.java类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
public class CustomResourceLoader implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void showResourceData() throws IOException
{
//This line will be changed for all versions of other examples
Resource banner = resourceLoader.getResource("file:D:/external/CamelContext.xml");
InputStream in = banner.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while (true) {
String line = reader.readLine();
if (line == null)
break;
System.out.println(line);
}
reader.close();
}
}
另外,在src/main/resources中创建applicationContext.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="customResourceLoader" class="main.CustomResourceLoader"></bean>
</beans>
附录-
1.支持开箱即用,2和3提供文件路径或配置要从中加载的路径的能力。请详细说明2和3的重试检查