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();
}
}