springboot获取配置文件中的属性(包含自定义的文件)

application.properties:

authname=shphyl
net.ebh=svnlan

默认的配置文件中可以直接获取

/**
 * 第一种方式 value("${name}")
 */
@Value("${authname}")
private String authname;

@RequestMapping("getname")
public String getAuthname() {
    return "my name is " + authname;
}
/**
 * 第二种方式直接注入Environment,通过environment.getProperty("name")来获取属性
 */
@Autowired
Environment environment;

@RequestMapping("get")
public String getname() {
    return environment.getProperty("net.ebh");
}
/**
 * 第三种直接获取配置文件
 */
public String getProperties(String key) {
    try {
        Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties"));
        return properties.getProperty(key);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@RequestMapping("getfile")
public String getFile() {
    String authname = getProperties("authname");
    String ebh = getProperties("net.ebh");
    return authname + "--" + ebh;
}

如果用户需要自定义配置文件,则需要配置来获取

my.properties

users.name=shphyl
users.age=12
users.sex=male

通过get set方法来获取

@Configuration
@ConfigurationProperties(prefix = "users")
@PropertySource("classpath:config/my.properties")
public class User {
    private String name;
    private int age;
    private String sex;
    //get set 省略
}

直接注入User通过get set即可获取各个属性

@Autowired
User user;

@RequestMapping("getproperties")
private String getMyproperties() {
    return user.getName() + "--" + user.getSex() + "--" + user.getAge();
}

完整代码

转载于:https://my.oschina.net/u/3125112/blog/874775

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值