博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
每日笔记---使用@ConfigurationProperties读取yml配置
阅读量:4699 次
发布时间:2019-06-09

本文共 1699 字,大约阅读时间需要 5 分钟。

1.添加pom依赖

org.springframework.boot
spring-boot-configuration-processor
true

 2.application.yml文件中添加需要配置的属性,注意缩进

Myyml:  username: cs  password: 123456  url: jdbc:mysql://localhost:3306/test  driver: com.mysql.jdbc.Driver

 3.新建一个类,@Component注解表明是组件,可被自动发现,@ConfigurationProperties注解之前是location属性表明配置文件位置,prefix表示读取的配置信息的前缀,但新版本中废除了location属性(网上说是1.5.2之后),故只写前缀,默认读取application.yml中数据。重点!!一定要在这个类中写getter和setter,否则配置中的属性值无法自动注入

package com.cs.background.util;import lombok.ToString;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "Myyml")public class User{    //数据库连接相关    private String url;    private String driver;    private String username;    private String password;    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getDriver() {        return driver;    }    public void setDriver(String driver) {        this.driver = driver;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}

 4.Controller类中执行自动注入,获取属性

//自动注入    @Autowiredprivate User user; //方法体内获取属性值String url=user.getUrl(); System.out.print(url);

 5.启动springboot入口类,调用对应controller对应的方法,控制台打印获取的值。

转载于:https://www.cnblogs.com/mycs-home/p/8352140.html

你可能感兴趣的文章
Greedy Pirate Gym - 101810M (lca)
查看>>
线性基(模板)
查看>>
bzoj-1030: [JSOI2007]文本生成器(ac自动机+dp)
查看>>
Bus Planning(状压DP)
查看>>
HDU 1828 Picture(线段树:扫描线 面积并)
查看>>
GCD - Extreme (II)(欧拉函数)
查看>>
Mondriaan's Dream POJ - 2411(状压dp)
查看>>
hdu-6703 array(主席树+set)
查看>>
LCM from 1 to n
查看>>
Fear Factoring Gym - 101652P(除法分块)
查看>>
Tree POJ - 1741 (点分治)
查看>>
Too Rich UVALive - 7183(贪心)
查看>>
欧拉定理证明&阶乘的逆元
查看>>
Prime Game Gym - 101981J(网络流/二分图)
查看>>
Teamwork Gym - 101492E (dp)
查看>>
No Link, Cut Tree! Gym - 101484F(dp)
查看>>
Coprimes Gym - 101492C(bitset)
查看>>
Partial Tree UVALive - 7190(完全背包)
查看>>
『深度应用』NLP机器翻译深度学习实战课程·零(基础概念)
查看>>
『开发技术』Windows极简安装使用face_recognition实现人脸识别
查看>>