打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SpringBoot的properties和yml两种配置方式, 配置注入参数, 以及配置文件读取失效的问题

SpringBoot支持两种配置方式,一种是properties文件,一种是yml

首先在pom文件中添加依赖:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-configuration-processor</artifactId>    <optional>true</optional></dependency>

1. yml配置文件绑定属性

使用properties可能会有中文乱码的问题,而使用yml可以避免这种情况
,yml的结构与json相似:
注意: yml冒号后要有空格,如果不加空格, 会导致yml配置读取失效


没有空格, 颜色都没有变色,显然有问题.

list用-,使用markdown的都应该熟悉,map是跟json一样key: value

user:   username: "小红"   password: "${user.username}123"   # 100以内的随机数   age: ${random.int(100)}   array : 1,2,3,4,5,6,7   strlist:      - list1     - list2     - list3   maplist:      - name: abc       value: abcValue     - name: 123       value: 123Value   map:      key1: value1     key2: value2server:  # 端口号   port: 8081

对应的User类:
@ConfigurationProperties这个注解,会将yml配置文件中属性名一样的值注入到User类对应的字段中, 相当于给每个字段加上@Value

@Component//@ConfigurationProperties设置前缀user@ConfigurationProperties(prefix = "user")public class User {    private int userid;    private String username;    private String password;    private int age;    private String[] array ;    private List<Map<String, String>> maplist = new ArrayList<Map<String, String>>();    private List<String> strlist = new ArrayList<>();    private Map<String, String> map = new HashMap<>();.....

比如password,对应的配置是user.password,所以设置一个前缀user

Controller层

@RestController@RequestMapping("/boot")public class MyController {    @Autowired    private User user;    @RequestMapping("/hello")    public String hello() {        return "这是第一个springboot";    }    @RequestMapping("/user")    public User getUser() throws JsonProcessingException {        ObjectMapper objectMapper = new ObjectMapper();        //测试加载yml文件        System.out.println("username: " + user.getUsername());        System.out.println("username: " + user.getPassword());        System.out.println("age: " + user.getAge());        System.out.println("array: " + objectMapper.writeValueAsString(user.getArray()));        System.out.println("maplist: " + objectMapper.writeValueAsString(user.getMaplist()));        System.out.println("strlist: " + objectMapper.writeValueAsString(user.getStrlist()));        System.out.println("map: " + objectMapper.writeValueAsString(user.getMap()));        return user;    }}

页面显示结果和控制台结果


2. properties配置方式

*.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码

public String getTitle3() {        try {            return new String(title3.getBytes("ISO-8859-1"), "UTF-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return title3;    }

2.1 @ConfigurationProperties方式

application.properties

com.zyd.type3=Springboot - @ConfigurationPropertiescom.zyd.title3=使用@ConfigurationProperties获取配置文件#mapcom.zyd.login[username]=zhangdeshuaicom.zyd.login[password]=zhenshuaicom.zyd.login[callback]=http://www.flyat.cc#listcom.zyd.urls[0]=http://ztool.cccom.zyd.urls[1]=http://ztool.cc/format/jscom.zyd.urls[2]=http://ztool.cc/str2imagecom.zyd.urls[3]=http://ztool.cc/json2Entitycom.zyd.urls[4]=http://ztool.cc/ua

在需要赋值的类上打上注解@ConfigurationProperties

@Component@ConfigurationProperties(prefix = "com.zyd")// PropertySource默认取application.properties// @PropertySource(value = "config.properties")public class PropertiesConfig {    public String type3;    public String title3;    public Map<String, String> login = new HashMap<String, String>();    public List<String> urls = new ArrayList<>();    // 转换编码格式    public String getTitle3() {        try {            return new String(title3.getBytes("ISO-8859-1"), "UTF-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return title3;    }    ....getter setter

main Application类:

@SpringBootApplication@RestControllerpublic class Applaction {    @Autowired    private PropertiesConfig propertiesConfig;    /**     *      * 第一种方式:使用`@ConfigurationProperties`注解将配置文件属性注入到配置对象类中     *      * @author zyd     * @throws UnsupportedEncodingException     * @since JDK 1.7     */    @RequestMapping("/config")    public Map<String, Object> configurationProperties() {        Map<String, Object> map = new HashMap<String, Object>();        map.put("type", propertiesConfig.getType3());        map.put("title", propertiesConfig.getTitle3());        map.put("login", propertiesConfig.getLogin());        map.put("urls", propertiesConfig.getUrls());        return map;    }    public static void main(String[] args) throws Exception {        SpringApplication application = new SpringApplication(Applaction.class);        application.run(args);    }}

运行结果:

{"title":"使用@ConfigurationProperties获取配置文件","urls":["http://ztool.cc","http://ztool.cc/format/js","http://ztool.cc/str2image","http://ztool.cc/json2Entity","http://ztool.cc/ua"],"login":{"username":"zhangdeshuai","callback":"http://www.flyat.cc","password":"zhenshuai"},"type":"Springboot - @ConfigurationProperties"}缩进量:    引号   显示控制  展开 叠起 2级 3级 4级 5级 6级 7级 8级 格式化JSON:{    "title": "使用@ConfigurationProperties获取配置文件",     "urls": [        "http://ztool.cc",         "http://ztool.cc/format/js",         "http://ztool.cc/str2image",         "http://ztool.cc/json2Entity",         "http://ztool.cc/ua"    ],     "login": {        "username": "zhangdeshuai",         "callback": "http://www.flyat.cc",         "password": "zhenshuai"    },     "type": "Springboot - @ConfigurationProperties"}

2.2 @Value注解方式

在需要赋值的属性上,加上@value注解
main Application类:

@SpringBootApplication@RestControllerpublic class Applaction {    @Value("${com.zyd.type}")    private String type;    @Value("${com.zyd.title}")    private String title;    /**     *      * 第二种方式:使用`@Value("${propertyName}")`注解     *      * @author zyd     * @throws UnsupportedEncodingException     * @since JDK 1.7     */    @RequestMapping("/value")    public Map<String, Object> value() throws UnsupportedEncodingException {        Map<String, Object> map = new HashMap<String, Object>();        map.put("type", type);        // *.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码        map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));        return map;    }    public static void main(String[] args) throws Exception {        SpringApplication application = new SpringApplication(Applaction.class);        application.run(args);    }}

运行结果

{"title":"使用@Value获取配置文件","type":"Springboot - @Value"}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解
SpringBoot-配置文件
springboot yml 配置文件注入Map,List
关于SpringBoot的application.yml的相关配置(自定义,开发,测试,正式)切换
Spring Boot第二弹,配置文件怎么造?
SpringBoot中这5种高大上的yml文件读取方式,你知道吗?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服