读取配置文件
import org.springframework.util.ResourceUtils;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 利用java自带库读取配置文件,键值对
* key = value
*/
public class ReadPropertiesUtil {
public static Properties getProperties(String propertiesPath) {
Properties properties = new Properties();
try {
if (propertiesPath == null)
propertiesPath = ResourceUtils.getURL("classpath:").getPath()+"response.properties";
InputStream inputStream = new BufferedInputStream(new FileInputStream(propertiesPath));
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
}
枚举类
public enum ReturnCode {
SUCCESS("SUCCESS_CODE", "SUCCESS_MSG"),
FAIL("FAIL_CODE", "FAIL_MSG"),
ERROR("ERROR_CODE", "ERROR_MSG"),
EXCEPTION("REQUEST_METHOD_UNSUPPORTED_CODE", "REQUEST_METHOD_UNSUPPORTED_MSG"),
URL_ERROR("UE_CODE", "UE_MSG");
private ReturnCode(String value, String msg){
this.val = value;
this.msg = msg;
}
public String val() {
return this.val;
}
public String msg() {
return this.msg;
}
private String val;
private String msg;
}
返回类
import lombok.Data;
import lombok.NonNull;
import java.util.Properties;
@Data
public class ReturnVO {
/**
* 自定义构造函数
*/
public ReturnVO(){
this.setCode(properties.getProperty(ReturnCode.SUCCESS.val()));
this.setMsg(properties.getProperty(ReturnCode.SUCCESS.msg()));
}
public ReturnVO(@NonNull ReturnCode code){
this.setCode(properties.getProperty(code.val()));
this.setMsg(properties.getProperty(code.msg()));
}
public ReturnVO(Object data){
this.setCode(properties.getProperty(ReturnCode.SUCCESS.val()));
this.setMsg(properties.getProperty(ReturnCode.SUCCESS.msg()));
this.setData(data);
}
public ReturnVO(ReturnCode code, String msg){
this.setCode(properties.getProperty(code.val()));
this.setMsg(msg);
}
public ReturnVO(ReturnCode code, String msg, Object data){
this.setCode(properties.getProperty(code.val()));
this.setMsg(msg);
this.setData(data);
}
private static Properties properties = ReadPropertiesUtil.getProperties(null);
@Override
public String toString() {
return "ReturnVO{" + "code='" + code + "'" +
", msg='" + msg + "'" +
", data=" + data +
'}';
}
private String code;
private String msg;
private Object data;
}
response.properties
SUCCESS_CODE=2000
SUCCESS_MSG=操作成功
FAIL_CODE=5000
FAIL_MSG=操作失败
NPE_CODE=5001
NPE_MSG=空指针异常
NRE_CODE=5002
NRE_MSG=返回值为空
RTE_CODE=5001
RTE_MSG=运行时异常
UE_CODE=404
UE_MSG=页面路径有误
REQUEST_METHOD_UNSUPPORTED_CODE=4000
REQUEST_METHOD_UNSUPPORTED_MSG=请求方式异常
BIND_EXCEPTION_CODE=4001
BIND_EXCEPTION_MSG=请求参数绑定失败
通过可配置,多语言操作
参考文档: