springboot讀取自定義properties配置文件


springboot讀取自定義properties配置文件

springboot版本:2.2.4

1、在src/maini/resources下創建配置文件sunnydiary.properties

#自定義配置文件測試
sunnydiary.name=SunnyDiary
sunnydiary.age=1.0.0
sunnydiary.home=China_HeNan

2、創建配置文件對應的bean類

@Configuration
@PropertySource("classpath:sunnydiary.properties")
@ConfigurationProperties(prefix="sunnydiary")
public class SunnyDiary {
    private String name;
    private String age;
    private String home;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getHome() {
        return home;
    }
    public void setHome(String home) {
        this.home = home;
    }
}

3、調用sunnydiary.properties方式一(推薦):

@RestController
@EnableConfigurationProperties(SunnyDiary.class)  // 注解class文件的方式
public class HelloWorldController {
    @Value("${sunnydiary.name}") 
    private String name;
    @Value("${sunnydiary.age}") 
    private String age;
    @Value("${sunnydiary.home}") 
    private String home;
    
    @RequestMapping("/hello")
    public String index() {
        return name + age + home;
    }
}

4、調用sunnydiary.properties方式二:

@RestController
public class HelloWorldController {
    @Autowired 
    SunnyDiary sunnyDiary;  // 使用注入類的方式
    
    @RequestMapping("/hello")
    public String index() {
        return sunnyDiary.getName() + sunnyDiary.getAge() + sunnyDiary.getHome();
    }
}

測試結果:

 


免責聲明!

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



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