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

测试结果:

 

posted @ 2020-02-09 18:04  NightsYoung  阅读(594)  评论(0编辑  收藏  举报