04-SpringBoot3入门-配置文件(多环境配置)
1、简介
在 SpringBoot 中,不同的环境(如开发、测试、生产)可以编写对应的配置文件,例如数据库连接信息、日志级别、缓存配置等。在不同的环境中使用对应的配置文件。
2、配置环境
# 开发环境
zbj:
user:
username: root
# 测试环境
zbj:
user:
password: 123456
3、激活环境
4、测试
User类
package com.sgu.pojo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 满堂花醉三千客,一剑寒霜十四州。
*
* @Author 中瑞
* @Date 2025/3/28 14:25
*/
@Component
@ConfigurationProperties(prefix = "zbj.user")
@Data
public class User {
private String username;
private String password;
private List<String> gfs;
}
UserController类
package com.sgu.controller;
import com.sgu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 满堂花醉三千客,一剑寒霜十四州。
*
* @Author 中瑞
* @Date 2025/3/28 14:26
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private User user;
@GetMapping("/show")
public User show() {
return user;
}
}
启动项目,浏览器输入地址:
http://127.0.0.1:8080/user/show
5、参考
146-springboot-多环境配置和激活_哔哩哔哩_bilibili