在使用多线程环境时,有些对象不是拖管在 Spring 容器中,但需要拿到 Bean 资源,是无法通过注入的方式的,就需要通过外部工具类来获取 Spring 上下文,再获取 Bean。
SpringContextUtil
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| @Component public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
public static void setApplicationContext(ApplicationContext applicationContext) { context = applicationContext; }
public static ApplicationContext getApplicationContext() { return context; }
public static <T> T getBean(String beanName) { return (T) getApplicationContext().getBean(beanName); }
public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); }
public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); }
}
|
若是 SSM 框架项目,则需要在 XML 文件中将 SpringContextUtil 配置为 Bean
1 2
| <bean id="springContextUtil" class="com.xxxxx.SpringContextUtil" scope="singleton" />
|
SpringUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component;
import java.util.Map;
@Slf4j @Component public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override public void setApplicationContext(ApplicationContext context) throws BeansException { if (applicationContext == null) { applicationContext = context; log.info("ApplicationContext init success,you can invoke by SpringUtil.getApplicationContext() to get ApplicationContext,init bean count=" + applicationContext.getBeanDefinitionCount() + ",bean=" + JSONObject.toJSONString(applicationContext.getBeanDefinitionNames())); } }
public static ApplicationContext getApplicationContext() { return applicationContext; }
public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); }
public static <T> T getBean(Class<T> clazz) { return applicationContext.getBean(clazz); }
public static <T> T getBean(String name, Class<T> clazz) { return applicationContext.getBean(name, clazz); }
public static <T> Map<String, T> getBeansOfType(Class<T> clazz) { return applicationContext.getBeansOfType(clazz); }
public static void publishEvent(ApplicationEvent event) { applicationContext.publishEvent(event); }
public static Environment getEnvironment() { return applicationContext.getEnvironment(); } }
|
@Slf4j是基于Lombok的插件。