# 实现Spring Boot指定外部配置文件

## 概述
在使用Spring Boot开发应用程序时,我们通常会需要使用外部配置文件来配置应用程序的一些参数,例如数据库连接信息、端口号等。本文将介绍如何指定外部配置文件以及如何在Spring Boot应用程序中使用外部配置文件。

## 操作步骤

| 步骤 | 操作 |
| ------ | ------ |
| 1 | 创建外部配置文件 |
| 2 | 配置Spring Boot应用程序以使用外部配置文件 |
| 3 | 在应用程序中读取外部配置文件的参数 |

### 步骤1: 创建外部配置文件
首先,我们要创建一个外部的配置文件来存储应用程序的配置信息。在Spring Boot中,外部配置文件通常存放在`src/main/resources`目录下,可以是`.properties`或`.yml`格式的文件。这里以`application.properties`为例,创建一个名为`custom.properties`的外部配置文件。

### 步骤2: 配置Spring Boot应用程序以使用外部配置文件
在Spring Boot应用程序的配置文件`application.properties`中,添加如下配置来指定外部配置文件的路径:

```java
spring.config.additional-location=classpath:/custom.properties
```

这样,Spring Boot会加载classpath下的`custom.properties`文件作为外部配置文件。

### 步骤3: 在应用程序中读取外部配置文件的参数
在应用程序中,我们可以使用`@Value`注解来读取外部配置文件中的参数。首先,在需要使用配置参数的类中注入`Environment`:

```java
import org.springframework.core.env.Environment;

@Autowired
private Environment env;
```

然后通过`env.getProperty`方法来获取外部配置文件中的参数值,例如:

```java
String customParam = env.getProperty("custom.param");
```

## 示例代码
下面是一个简单的示例代码,演示了如何使用外部配置文件以及在应用程序中读取外部配置文件的参数:

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class AppConfig {

@Autowired
private Environment env;

public static void main(String[] args) {
SpringApplication.run(AppConfig.class, args);
}

@PostConstruct
public void init() {
String customParam = env.getProperty("custom.param");
System.out.println("Custom Param: " + customParam);
}

}
```

在这个示例中,我们定义了一个名为`custom.param`的配置参数,在外部配置文件`custom.properties`中设置了该参数的值。当应用程序启动时,通过`@PostConstruct`注解的`init`方法读取并输出`custom.param`的值。

通过以上步骤和示例代码,你可以轻松实现Spring Boot指定外部配置文件的功能。希望对你有所帮助!