springboot properties参数配置

springboot为我们提供了application.properties文件,我们的key value值可以存放在此文件中,springboot会自动加载application.properties文件和application*.yml文件但是很多情况下我们会自定义配置文件,由于自定义的配置文件spring并不能帮我们加载所以需要我们手动让它加载


1.application.propertis属性的读取

首先在application.properties文件中定义我们的key value值


然后定义属性类Aliproperties

package com.example.demo.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Configuration;

import org.springframework.stereotype.Component;

@Component

@ConfigurationProperties(prefix="com.ali")

public class Aliproperties {

private String address;

private String mail;

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

public String getMail() {

return mail;

}

public void setMail(String mail) {

this.mail = mail;

}

}


使用


使用postman请求


成功获取key value 值


二、自定义配置文件的读取

由于自定义配置文件spring不能帮我们加载所以需要加上注解来让spring加载

首先在resource目录下新建config文件夹

新建properties文件并定义我们的key value值

test1=213

test2=222

定义TestProperties类 加上@PropertySource("classpath:config/test.properties")注解注入我们的文件

/**

*

*/

package com.example.jsp.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

/**

* @author ****

*

*/

@Configuration

@PropertySource("classpath:config/test.properties")

@ConfigurationProperties

public class TestProperties {

private String test1;

private String test2;

public String getTest1() {

return test1;

}

public void setTest1(String test1) {

this.test1 = test1;

}

public String getTest2() {

return test2;

}

public void setTest2(String test2) {

this.test2 = test2;

}

}

在启动类或者此类加上@EnableConfigurationProperties(TestProperties.class)注解

使用类似application.properties文件

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,268评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,999评论 6 342
  • 配置文件解析(下) 原创者:文思 一、yml(YAML Ain’t Markup Language)基本用法...
    文思li阅读 2,054评论 0 2
  • 我一直想和人身边的人处好关系,平常话也不多,所以很多时候也会一直想聊什么话题 但是最近有一个体验,就是不需要你多么...
    张志鹏_7bba阅读 139评论 1 1
  • 突然很怀念小时候洗完澡,拿着外公外婆辈们用的蒲扇,搬着小椅子去院子里乘凉的时光。数着天上的星星,蒲扇一扇一扇的,跟...
    永远清醒Q阅读 434评论 0 0