springboot基础——配置文件
配置文件的属性配置以及如何映射到实体类
——使用spring-boot-configuration-processor更优雅地读取配置文件
方法一:简单的配置文件读取
1.在配置文件application.properties或者application.yml中声明配置(application.properties示例如下:)
author.name=test
2.在代码中读取配置信息
@Value("${author.name}")
private String authorName;
方法二:使用spring-boot-configuration-processor(推荐)
第一步:引入pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
第二步:定义配置文件,文件放在resources目录下,文件格式:文件名.properties(如:author.properties),文件内容示例如下:
author.name=你的名字 author.email=你的邮箱地址
第三步:定义配置类,添加注解
@Configuration
@ConfigurationProperties(prefix = "author")
@PropertySource(value = "classpath:author.properties")
public class AuthorConfig {
private String name;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第四步:使用
@RestController
public class HelloController {
@Autowired
private AuthorConfig authorConfig;
@Value("${author.name}")
private String AuthorName;
@GetMapping("/hello")
public void Hello(){
System.out.println(AuthorName);
System.out.println(authorConfig.getName());
System.out.println(authorConfig.getEmail());
}
}
懵懵懂懂迷迷糊糊

浙公网安备 33010602011771号