这段时间在做项目时遇到端口号要写在配置文件中的问题,通过度娘了解了一下,在这里简要写一下自己的体会,希望对大家有所帮助
1.作用
用来加载指定的配置文件和外部文件
2.属性
PropertySource有以下几个属性
1.value为要加载的文件,可以是多个当以classpath开头时,程序会自动到classpath中读取,当以file开头时,会加载外部的文件
2.name是表示要加载文件的名称,这里要加载的配置文件必须是 唯一的不能是多个
3.encoding,设置编码,我们一般用utf-8
4.ignoreResourceNotFound,这个属性的意思是当加载的配置文件不存在时,是否报错默认false,当为true时表示文件不存在不报错,为false时表示文件不存在报错
@PropertySource(value= {"classpath:cinterface.properties","file:config/cinterface.properties"},encoding="UTF-8",ignoreResourceNotFound=true)
3.使用
@PropertySource要和@Value配合使用,@Value注解的属性为配置文件的键,对应下面的属性
配置文件
cinterface.port=10023
实体类
@Value("${cinterface.port}")
private String port;
4.实例
配置文件
cinterface.port=10023
cinterface.LSCID=1
实体类(这里说明一下实体类好像这能定义成String类型,我定义成int会报错)
package com.modou.cinterface.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value= {"classpath:cinterface.properties","file:config/cinterface.properties"},encoding="UTF-8",ignoreResourceNotFound=true)
public class CinterfaceConfig {
@Value("${cinterface.port}")
private String port;
@Value("${cinterface.LSCID}")
private String LSCID;
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getLSCID() {
return LSCID;
}
public void setLSCID(String lSCID) {
LSCID = lSCID;
}
}
如有错误或不恰当处欢迎指出