springboot中多种获取properties的方式

在项目开发中常常会用到配置文件,配置文件的存在解决了很大一份重复的工做。今天就分享四种在Springboot中获取配置文件的方式。spring

注:前三种测试配置文件为springboot默认的application.properties文件springboot

1、@ConfigurationProperties方式app

application.properties测试

com.xh.username=sher
com.xh.password=123456

新建PropertiesConfigspa

@Component
@ConfigurationProperties(prefix = "com.xh")//获取配置文件中以com.xh开头的属性
public class PropertiesConfig {
    private String username;
    private String password;
    //get set 省略
}

启动类PropertiesApplication开发

@SpringBootApplication
@RestController
public class PropertiesApplication {
    @Autowired
    PropertiesConfig propertiesConfig;

    public static void main(String[] args) {
        SpringApplication.run(PropertiesApplication.class, args);
    }
    @GetMapping("config")
    public String getProperties() {
        String username = propertiesConfig.getUsername();
        String password = propertiesConfig.getPassword();
        return username+"--"+password;
    }
}

测试结果get

2、使用@Value注解方式io

启动类class

@SpringBootApplication
@RestController
public class PropertiesApplication {
    @Value("${com.xh.username}")
    private String username;
    @Value("${com.xh.password}")
    private String password;
    @GetMapping("config")
    private String getProperties(){
        return username+"---"+password;
    }

测试结果:配置

3、使用Environment

启动类

@SpringBootApplication
@RestController
public class PropertiesApplication {
    @Autowired
    Environment environment;

    @GetMapping("config")
    private String getProperties() {
        String username = environment.getProperty("com.xh.username");
        String password = environment.getProperty("com.xh.password");
        return username + "-" + password;
    }

测试结果:

相关文章
相关标签/搜索