gpt4 book ai didi

java - Spring Boot 中的配置文件位于 jar 文件之外

转载 作者:行者123 更新时间:2023-12-02 11:10:50 24 4
gpt4 key购买 nike

我有一个 Spring boot Camel 应用程序,其目录结构如下

enter image description here

我想把这个项目转换成jar文件。但我想要在我的 jar 之外有 3 个文件,这样当配置更改时我不需要一次又一次地重新部署我的应用程序。这 3 个文件是

  1. 应用程序属性

  2. CamelContext.xml

  3. sql.properties

    我可以灵活地对文件位置的路径进行硬编码。谁能帮助我如何实现这一目标?

最佳答案

既然我已经解决了这个问题,我就会为任何试图实现同样目标的人发布解决方案。

@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>

附录 -

关于java - Spring Boot 中的配置文件位于 jar 文件之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com