如何自定义缓存spring bean1
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
58public class SpringBeanHolder implements ApplicationContextAware {
private static ApplicationContext context;
private static ConcurrentHashMap<String, Object> cachedBeans = new ConcurrentHashMap<>(7000);
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringBeanHolder.context = context;
}
public static <T> T getBean(String beanName) throws NullPointerException{
T bean = getBeanMaybeNull(beanName);
if (bean == null) throw new NullPointerException("bean[" + beanName + "] is not exist in spring container");
return bean;
}
"unchecked") (
public static <T> T getBeanMaybeNull(String beanName) {
notEmpty(beanName, beanName + " bean name is required");
checkState(context != null, "spring application context is not injected");
T bean = (T) cachedBeans.get(beanName);
if (bean == null) {
bean = cache(beanName, (T) context.getBean(beanName));
}
return bean;
}
"unchecked") (
private static <T> T cache(String beanName, T exist) {
if (exist == null) return null;
T bean = (T) cachedBeans.putIfAbsent(beanName, exist);
if (bean == null) {
bean = exist;
}
return bean;
}
"unchecked") (
public static <T> T getBean(Class<?> beanType) {
String clazzName = beanType.getName();
T bean = getBeanMaybeNull(clazzName);
if (bean == null) { // 对于非注入的类, 直接new...
try {
bean = (T) beanType.newInstance();
cache(clazzName, bean);
} catch (Exception e) {
throw new RuntimeException("cannot get instance from class:" + clazzName, e);
}
}
return bean;
}
}