常用的代码片段

获取UTC时间

Calendar cal = Calendar.getInstance();
// utc时间和本地时间差
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// 夏令时差
int dstOffset = cal.get(Calendar.DST_OFFSET);
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
System.out.println(cal.getTimeInMillis());


获取Spring容器的bean

方法1

ContextLoaderListener.getCurrentWebApplicationContext().getBean("beanName");

方法2

public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
SpringUtil.applicationContext = arg0;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static String getMessage(String code, Object[] args, Locale locale) {
try {
return applicationContext.getMessage(code, args, locale);
} catch (NoSuchMessageException e) {
return "'" + code + "' is not defined in " + locale.toString();
}
}
}


单例的写法

Double Check

public class Singleton {
private volatile static Singleton instance; //声明成 volatile
private Singleton (){}
public static Singleton getSingleton() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

饿汉式

public class Singleton{
//类加载时就初始化
private static final Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}

Java获取文件

获取classpath下的文件

File database = new File(this.getClass().getResource("/GeoLite2-Country.mmdb").toURI());