美文网首页javaweb核心技术
springboot properties参数配置

springboot properties参数配置

作者: 上岸之路 | 来源:发表于2018-09-07 18:23 被阅读72次

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文件

相关文章

网友评论

    本文标题:springboot properties参数配置

    本文链接:https://www.haomeiwen.com/subject/cadcgftx.html