springboot 创建自定义配置文件
时间: 2023-09-24 09:11:32 浏览: 61
要创建自定义配置文件,你可以按照以下步骤进行:
1. 在 src/main/resources 目录下新建一个 properties 文件或 yaml 文件,例如 myconfig.properties 或 myconfig.yaml。
2. 在文件中定义你需要的配置项,例如:
```
myconfig.username=admin
myconfig.password=123456
```
或者
```
myconfig:
username: admin
password: 123456
```
3. 在 Spring Boot 应用中通过 `@ConfigurationProperties` 注解加载并使用这些配置项,例如:
```
@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private String username;
private String password;
// 省略 getter 和 setter 方法
}
```
4. 在需要使用这些配置项的地方注入 `MyConfig` 对象,例如:
```
@RestController
public class MyController {
@Autowired
private MyConfig myConfig;
@GetMapping("/config")
public String getConfig() {
return "username: " + myConfig.getUsername() + ", password: " + myConfig.getPassword();
}
}
```
这样就可以在 Spring Boot 应用中使用自定义配置文件了。