在非SpringBean类中从ApplicationContext取出Bean
本文的主要目的是从spring中取出bean,然后赋值给一个util类,util是静态工具类,不用放到spring注册到bean。所以它也拿不到spring bean。为了让util单方面的拿到bean,可以这么做
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
| @Component public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; }
public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; }
@SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); }
@SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); @SuppressWarnings("rawtypes") Map beanMaps = applicationContext.getBeansOfType(clazz); if (beanMaps != null && !beanMaps.isEmpty()) { return (T) beanMaps.values().iterator().next(); } else { return null; } }
private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } }
}
|
通过一个中介bean,在其他util中,就可以使用这个中介bean取出spring上下文中的bean
1 2
| private static final RedisTemplate<String, Object> REDIS_TEMPLATE = SpringContextHolder .getBean(RedisTemplate.class);
|