(转)SpringBoot 打包为war包启动时导入外部配置文件

本文介绍了一种在Spring Boot项目中使用WAR包部署时,通过Tomcat加载指定位置application.properties配置文件的方法。通过创建LocalSettingsEnvironmentPostProcessor类并配合spring.factories文件,实现了外部配置文件的优先加载。

转自:http://blog.youkuaiyun.com/nijiayy/article/details/78457800

 

最近在做一个SpirngBoot的项目,要求服务器部署的时候使用tomcat启动war包的时候需要导入一个指定位置的application.properties文件。在网上查找了相关的问题之后,发现大部分都是基于jar包的,同样的方法war包下并不适用。 
后来发现了一个方法,可以为完美解决这个问题。 
这里写图片描述 
在你的项目文件夹下,创建一个configuration文件夹用于存储各种SpringBoot的配置文件,然后新建一个Java类LocalSettingsEnvironmentPostProcessor。

package com.altynai.xxxxxx.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor{
    private static final String LOCATION = "C:\\xxxx\\application.properties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
        File file = new File(LOCATION);
//        File file = new File(System.getProperty("user.home"), LOCATION);
//        System.out.println("user.home" + System.getProperty("user.home"));
        if (file.exists()) {
            MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
//            System.out.println("Loading local settings from " + file.getAbsolutePath());
            Properties properties = loadProperties(file);
//            System.out.println(properties.toString());
            propertySources.addFirst(new PropertiesPropertySource("Config", properties));
        }
    }

    private Properties loadProperties(File f) {
        FileSystemResource resource = new FileSystemResource(f);
        try {
            return PropertiesLoaderUtils.loadProperties(resource);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex);
        }
    }
}

这个java类的作用就是根据指定的配置文件路径,读取文件,添加到程序运行的环境中。注意,根据我的测试,这里导入的外部配置文件只能是.properties的文件,如果是.yml的话会有问题。 
然后在你的resources文件夹下创建一个文件夹名为META-INF,在里面创建一个spring.factories的文件,文件内容如下:

org.springframework.boot.env.EnvironmentPostProcessor=com.altynai.xxxxx.configuration.LocalSettingsEnvironmentPostProcessor

这个文件的作用就是设置SpringBoot服务启动的时候调用我们刚才写的那个Java类。

至此,你的war包在使用tomcat启动的时候就应该可以读取制定位置的外部文件了。我的文件结构如下,仅供参考 
这里写图片描述 
这里还需要说明的是假设你原本的配置文件的设置属性与导入了外部配置文件的设置属性重复了最终系统运行起来使用的是哪一个? 
答案是,看两个配置文件加入程序环境的先后顺序,后面的会覆盖前面的。 
上面的Java类中有这个一段代码,这里的意思就是,外部的文件是最先导入的。

 propertySources.addFirst(new PropertiesPropertySource("Config", properties));

如果设置为下面的这个

 propertySources.addLast(new PropertiesPropertySource("Config", properties));

则表示最后导入外部配置文件。

参考链接: 
[1] https://www.youtube.com/watch?v=uof5h-j0IeE&feature=youtu.be&t=1h17m46s 
[2] https://www.youtube.com/watch?v=uof5h-j0IeE&feature=youtu.be&t=1h17m46s

 

### 修改 IntelliJ IDEA 中项目的打包配置从 JAR 到 WAR 在开发过程中,有时需要改变项目最终生成的文件类型,例如从 JAR 文件更改为 WAR 文件。这通常涉及到调整构建工具(如 Maven 或 Gradle)的相关设置。 对于基于 Maven 的项目,在 `pom.xml` 文件内修改 `<packaging>` 标签的内容即可实现这一变: ```xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> ... <packaging>war</packaging> ... </project> ``` 完成上述更改后,重新导入Maven工程以使改动生效[^1]。 如果使用的是 Spring Boot 应用程序,则还需要确保移除默认嵌入式的 Tomcat 容器插件,并添加适合 Web 应用的支持库。具体操作是在 `pom.xml` 中排除 spring-boot-starter-tomcat 并加入 javax.servlet API 及其实施版本,如下所示: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 移除Tomcat容器 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- 添加Servlet支持 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> ``` 最后一步是确认应用主类继承自 `SpringBootServletInitializer` 类并重写 configure 方法来适应外部 Servlet 容器环境的要求: ```java import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } } ``` 执行以上步骤之后,当再次尝试构建项目时将会得到一个 `.war` 文件而不是之前的 `.jar` 文件[^2]。 为了验证新的 WAR 文件是否成功创建,可以在命令行中进入项目的根目录并通过以下指令触发构建过程: ```bash mvn clean package ``` 构建完成后,应该能够在 `/target` 目录下看到新产生的 `.war` 文件[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值