SpringBoot读取配置文件

发布于:2024-03-11 ⋅ 阅读:(36) ⋅ 点赞:(0)

SpringBoot读取配置文件

这里以minio作为示例

minio坐标

<!-- knife4j -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
    <version>4.3.0</version>
</dependency>

创建spring配置文件

server:
  port: 8800
spring:
  application:
    name: bunny-demo-minio

bunny:
  minio:
    endpointUrl: "http://192.168.3.10:9000"
    bucket-name: sky
    accessKey: "bunny"
    secretKey: "02120212"

读取配置文件

创建config包,并创建MinioConfig,读取以bunny.minio开头前缀内容

使用@Bean注入ioc到容器中

@Data
@Configuration
@ConfigurationProperties(prefix = "bunny.minio")
public class MinioConfig {
    private String endpointUrl;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder().endpoint(endpointUrl).credentials(accessKey, secretKey).build();
    }
}

读取成功
在这里插入图片描述

使用@Value方式读取,如果我们在项目中,还想读取配置内容可以使用@Value方式

如配置文件

需要读取myPassword字段

server:
  port: 8800
spring:
  application:
    name: bunny-demo-minio

bunny:
  minio:
    endpointUrl: "http://192.168.3.10:9000"
    bucket-name: sky
    accessKey: "bunny"
    secretKey: "02120212"

  myPassword: "123456"

在java文件中申明字段,注意一定要加上${}

@Data
@Configuration
@ConfigurationProperties(prefix = "bunny.minio")
public class MinioConfig {
    private String endpointUrl;
    private String accessKey;
    private String secretKey;
    private String bucketName;
    @Value("${bunny.myPassword.password}")
    private String myPassword;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder().endpoint(endpointUrl).credentials(accessKey, secretKey).build();
    }
}

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到