Spring中的参数统一配置

情景:

在一个Spring项目中通常存在如数据库 url,账号,密码等需要人为配置的参数,此类参数并非固定,很可能会发生变化,所以一般会统一集中在一个文件中,方便统一管理

解决方法

1.在项目resources目录下,创建application.yml文件

复制代码
minio:
  endpoint: http://<hostname>:<port>
  access-key: <access-key>
  secret-key: <secret-key>
  bucket-name: <bucket-name>

2.创建参数类

复制代码
设置前缀,yml文件的参数会自动映射到类中的参数上(自动开启驼峰命名)
@ConfigurationProperties(prefix = "minio")
@Data
public class MinioProperties {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;
}

3.创建配置类

复制代码
@Configuration
//@EnableConfigurationProperties({MinioProperties.class})
//在指定包下,自动查找,引用之前设置的参数类
@ConfigurationPropertiesScan("com.atguigu.lease.common.minio")
public class MinioConfiguration {
    @Autowired
    private MinioProperties minioProperties;


    @Bean
    public MinioClient minioClient() {
        return new MinioClient.Builder().endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
    }
}
相关推荐
陈随易19 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
IT_陈寒21 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰1 天前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
这个DBA有点耶1 天前
NULL不是空——数据库里最反直觉的设计,90%新人踩过的坑
数据库·mysql·代码规范
用户8356290780511 天前
Python 实现 PDF 文件加密与解密方法
后端·python
小满zs1 天前
Go语言第二章(小无相功)
后端·go
用户8356290780511 天前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k1 天前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
妙码生花1 天前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
贰先生1 天前
Xiuno BBS X版 用户封禁系统
后端