抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

本文的主要目的是从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;

// 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}

// 取得存储在静态变量中的ApplicationContext.
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}

// 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}

// 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
// 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
// 如果有多个Bean符合Class, 取出第一个.
@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);

评论