您的位置:首页 > 编程语言 > Java开发

springboot读取自己定义的配置文件的方式以及使用joda_time来处理时间日期

2017-11-30 08:57 1156 查看
总的来说呢,有两种方式,一种是原始的方式,即使用PropertiesUtils来读取配置文件。

第二种就是使用springboot的注解的方式来读取配置文件。

1、原始方式处理属性和时间日期:

工具类:

package com.imooc.project.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class PropertiesUtil {

private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

private static Properties props;

static {
String fileName = "mmall.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常",e);
}
}

public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}

public static String getProperty(String key,String defaultValue){

String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}

}


  属性文件放在resource下面



。这是传统的处理方式。

看下joda_time的工具类:

引入joda_time的jar包:

package com.imooc.project.util;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;

//利用还joda_time来处理时间日期
public class DateUtil {
//joda-time
//str->Date
//Date->str
public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";

public static Date strToDate(String dateTimeStr,String formatStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}
//将Date类型转为String类型
public static String dateToStr(Date date,String formatStr){
if(date == null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(formatStr);
}
//重写第一个方法,将string类型转为Date类型
public static Date strToDate(String dateTimeStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}
public static String dateToStr(Date date){
if(date == null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(STANDARD_FORMAT);
}

}


  

2、目前先说这两种原始方式,后面会补充springboot的使用方式。

(1)、springboot如何读取工具类的?

(2)、springboot如何处理时间日期类型的?

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: