在Spring Boot中将配置文件放在jar文件之外

时间:2018-06-01 06:51:47

标签: java spring spring-boot jar apache-camel

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

enter image description here

我想将此项目转换为jar文件。但我想在我的jar外面有3个文件,这样我就不需要在配置发生变化时一次又一次地重新部署我的应用程序。 这3个文件是

  1. application.properties
  2. CamelContext.xml
  3. sql.properties

    我可以灵活地对文件位置的路径进行硬编码。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

由于我已经解决了这个问题,我会为那些试图达到同样目标的人发布解决方案。

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

附录 -