springboot 读取application.properties配置中信息的三种方法

*注:想了解指定义properties配置* 点击

application.properties配置信息

在这里插入图片描述

第一种:使用@value:可以注入具体的配置信息

优点:单个使用方便,灵活性高

缺点:获取配置文件信息多,需要些大量的@Value,不利于开发,增加开发者的工作量

创建application.properties配置

name=lishi
com.user.name=zhangshan
com.user.sex=nan

1.使用@Value读取配置

@RestController
public class demoController {
    /*
        ps:获取配置文件的两种方法
        1.spring boot 默认获取application.properties文件数据
            1.1:使用@value可以获取配置信息的值  
     */

    //第一种方法
    @Value("${name}")
    private String name1;

    //第一种方法
    @GetMapping("/hello1")
    public  String hello(){
        System.out.println("name1="+name1);
        return name1;
    }
    }

第二种:注入Environment 对象,并通过Environment的getProperty 方法获取配置信息的值

@RestController
public class demoController {
    /*
        ps:获取配置文件的两种方法
        1.spring boot 默认获取application.properties文件数据
            1.1:使用@value可以获取配置信息的值
            1.2.注入Environment 对象,并通过Environment的getProperty 方法获取配置信息的值
     
     */
    //第二种方法
    //注入对象
    @Autowired
    private Environment environment;

    //第二种方法
    @GetMapping("/hello2")
    public  String hello2(){
        String name2 =environment.getProperty("name");
        System.out.println("name2="+name2);
        return name2;
    }

}

第三种:

1.创建User 对象

2.使用@ConfigurationProperties(prefix = “com.user”)获取application.properties配置信息前缀

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
//获取application.properties配置信息前缀
@ConfigurationProperties(prefix = "com.user")
@Component
public class User {
    private  String name;
    private String sex;

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

}
@RestController
public class demoController {

    //第三种方法
    @Autowired
    private User user;

    //第三种方法
    @GetMapping("/hello3")
    public  String hello3(){
        String name = user.getName();

        System.out.println("name="+name);
        return user.getSex();
    }

}


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐