import org.springframework.context.ApplicationContext;
//单例工具类最佳实践,以ApplicationContext为例
public class ApplicationContextUtil {
private static ApplicationContext applicationContext;
//利用private关键字防止外部直接new 在方法内部抛出异常,避免利用反射实例化对象
private ApplicationContextUtil() throws Exception {
throw new InstantiationException("ApplicationContextUtil不允许实例化");
}
//采用dcl(double check lock)模式,尽可能地减少加锁次数以及防止后续线程抢到锁后再次给对象赋值故在临界区再次判断,使得方法只能被调用一次
public static void init(ApplicationContext applicationContext) {
if (ApplicationContextUtil.applicationContext != null) return;
synchronized (ApplicationContextUtil.class) {
if (ApplicationContextUtil.applicationContext != null) return;
ApplicationContextUtil.applicationContext = applicationContext;
}
}
//避免了后期在调用此方法时候出现空指针异常,直接抛出异常
public static ApplicationContext getApplicationContext() {
if (applicationContext == null) throw new RuntimeException("applicationContext不允许为null");
return applicationContext;
}
//方法重载,复用getApplicationContext,拿到ApplicationContext的实现类,Class参数限制为只能是ApplicationContext的实现类
@SuppressWarnings("unchecked")
public static <T extends ApplicationContext> T getApplicationContext(Class<T> clazz) {
return (T) getApplicationContext();
}
}
单例工具类最佳实践,以ApplicationContext为例
于 2024-07-31 13:19:47 首次发布