SpringBoot讀取.yml/.properties配置文件


.properties文件內容如下:

test.name=test
test.msg=123456

.yml文件內容如下:

spring:
  test:
    name: test
    msg: 123456

一、@Configuration+@PropertySource+@Value讀取.properties

讀取類代碼如下:

@Configuration
@PropertySource("classpath:test.properties")
public class Test {
      @Value("${test.name}")
      private String name;
      @Value("${test.msg}")
      private String msg;
}

二、@Component+@ConfigurationProperties讀取.yml

屬性名要和配置文件名一致,且要有Getter and Setter,讀取類代碼如下:

@Component
@ConfigurationProperties(prefix = "spring.test")
public class Test {
    private String name;
    private String msg;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

三、@Component+Environment讀取.yml

讀取類代碼如下:

import org.springframework.core.env.Environment;
@Component
public class Test {
    @Autowired
    private Environment environment;
    @Bean
    public JedisCluster getJedisCluster() {
        System.out.println("name:" + environment.getProperty("spring.test.name")); 
        ...
     }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM