导读 在springBoot中,可能还需要获取自定义的配置。

读取配置文件

在使用maven项目中,配置文件会放在resources根目录下。
我们的springBoot是用Maven搭建的,所以springBoot的默认配置文件和自定义的配置文件都放在此目录。
springBoot的 默认配置文件为 application.properties 或 application.yml,这里我们使用 application.properties。

首先在application.properties中添加我们要读取的数据。
springBoot支持分层结构。
例如:

web:
  pancm:
    title: SpringBoot
    description: test

注意前面的空格!

在application.properties添加完之后,我们便在代码中进行读取。
这里我们使用@Value 方式。
首先在类中添加 @Component、@ConfigurationProperties这两个注解。
第一个注解表示这个类是获取配置文件,第二个注解表示从配置文件中获取的数据转换为对象。因为我们使用了层级结构,获取web.pancm目录下的参数,所以我们再加上prefix = "web.pancm"这个表示获取这之后的数据,就避免了下面在重复书写。
那么代码如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 
* Title: MyProperties
* Description:
* 从application.properties 获取 配置
* Version:1.0.0  
* @author pancm
* @date 2018年1月11日
 */
@Component
@ConfigurationProperties(prefix = "web.pancm")  
public class MyProperties {
	/**
	 * 获取个人标题
	 * 
	 */
	@Value("${title}")
	private String title;
	
	/**
	 * 获取个人描述
	 */
	@Value("${description}")
	private String description;

	/** get和set略 */

}

本类中可以直接获取该属性,不过在外部类调用的时候,需要添加@Autowired。

例如:

@Autowired
MyProperties myProperties;


System.out.println(myProperties.getTitle());
System.out.println(myProperties.getDescription());

上面的是获取application.properties中的方法。
如果想自定义配置文件和属性的话,只需再添加一个@PropertySource注解就可,然后添加 value属性,指向文件路径即可。
例如:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
 * 
* Title: MyConfig
* Description:
* 自定义配置文件 
* Version:1.0.0  
* @author pancm
* @date 2018年1月20日
 */
@Component 
@ConfigurationProperties(prefix = "myconfig") 
@PropertySource(value = "classpath:myconfig.proferties")
public class MyConfig {  
  
    @Value("${test}") 
    private String test;  
  
    public String getTest() {  
        return test;  
    }  
  
    public void setTest(String test) {  
        this.test = test;  
    }  
}

调用方法同上!

注: 之前的springBoot版本的@ConfigurationProperties注解可以使用 locations 方法来指定自定义配置文件路径,不过在 springBoot 1.5以上的就已经不支持 location属性,所以这里使用的是PropertySource。

原文来自:https://www.cnblogs.com/xuwujing/p/8485832.html

本文地址:https://www.linuxprobe.com/springboot-configuration-file.html编辑:薛鹏旭,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/