springboot 使用@ConfigurationProperties注入配置属性

时间:2023-03-10 01:38:31
springboot 使用@ConfigurationProperties注入配置属性

导入依赖,让springboot支持@ConfigurationProperties 注解

    <!-- 支持 @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>{SpringBoot的版本}</version>
</dependency>

配置文件:

connection:
username: admin
password: kyjufskifas2jsfs
remoteAddress: 192.168.1.1

配置文件注册类:

@Component
@ConfigurationProperties(prefix="connection")
public class Properties {
private String username;
private String remoteAddress;
private String password ; public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} }

使用时直接注入即可:

@RequestMapping("/test")
@RestController
public class TestController { @Autowired
private Properties properties; @GetMapping("/test")
public void test(){
System.out.println("===================="+properties.getPassword());//====================kyjufskifas2jsfs
}
}