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

測試結果:

相關文章
相關標籤/搜索