springboot读取属性文件(*.properties)

#######################方式一######################### 
com.zyd.type3=Springboot - @ConfigurationProperties 
com.zyd.title3=使用@ConfigurationProperties获取配置文件
 #map 
com.zyd.login[username]=zhangdeshuai 
com.zyd.login[password]=zhenshuai 
com.zyd.login[callback]=http://www.flyat.cc 
#list 
com.zyd.urls[0]=http://ztool.cc 
com.zyd.urls[1]=http://ztool.cc/format/js 
com.zyd.urls[2]=http://ztool.cc/str2image 
com.zyd.urls[3]=http://ztool.cc/json2Entity 
com.zyd.urls[4]=http://ztool.cc/ua 
#######################方式二######################### 
com.zyd.type=Springboot - @Value 
com.zyd.title=使用@Value获取配置文件 
#######################方式三######################### 
com.zyd.type2=Springboot - Environment 
com.zyd.title2=使用Environment获取配置文件

一、@ConfigurationProperties方式

自定义配置类:PropertiesConfig.java

@Component 
@ConfigurationProperties(prefix = "com.zyd")
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 getType3() {
		return type3;
	}

	public void setType3(String type3) {
		this.type3 = type3;
	}

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

	public void setTitle3(String title3) {
		this.title3 = title3;
	}

	public Map<String, String> getLogin() {
		return login;
	}

	public void setLogin(Map<String, String> login) {
		this.login = login;
	}

	public List<String> getUrls() {
		return urls;
	}

	public void setUrls(List<String> urls) {
		this.urls = urls;
	}
}

另外一种方式:

自定义citycode.properties

#List properties
citycode.list[0]=www
citycode.list[1]=localhost
citycode.list[2]=wuhan
citycode.list[3]=tianjin


#Map Properties
citycode.map.www=4201
citycode.map.wuhan=4201
citycode.map.tianjin=1200

 设置一个类去读取properties

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Configuration
@PropertySource("classpath:citycode.properties")
@ConfigurationProperties(prefix = "citycode")
public class CityCodeConfig {

    private List<String> list = new ArrayList<>();

    private Map<String, String> map = new HashMap<>();

}

猜你喜欢

转载自blog.csdn.net/qq_15140841/article/details/82177382