com.jn.agileway.spring.utils.SpringContextHolder Maven / Gradle / Ivy
package com.jn.agileway.spring.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.concurrent.CountDownLatch;
/**
* SpringContextHolder 这个类,不是单例的。
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
private static final CountDownLatch downLatch = new CountDownLatch(1);
@Override
public void setApplicationContext(ApplicationContext appContext) throws BeansException {
if (SpringContextHolder.applicationContext == null) {
SpringContextHolder.applicationContext = appContext;
downLatch.countDown();
}
}
public static ApplicationContext getApplicationContext() {
if (applicationContext != null) {
return applicationContext;
}
try {
downLatch.await();
return applicationContext;
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
public static T getBean(String name) {
return (T) getApplicationContext().getBean(name);
}
public static T getBean(Class clazz) {
return getApplicationContext().getBean(clazz);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy