|
@@ -0,0 +1,68 @@
|
|
1
|
+package com.zhaxd.utils;
|
|
2
|
+
|
|
3
|
+import org.springframework.context.ApplicationContext;
|
|
4
|
+import org.springframework.context.ApplicationContextAware;
|
|
5
|
+
|
|
6
|
+import java.lang.annotation.Annotation;
|
|
7
|
+import java.util.ArrayList;
|
|
8
|
+import java.util.List;
|
|
9
|
+import java.util.Map;
|
|
10
|
+
|
|
11
|
+/**
|
|
12
|
+ * 以静态变量保存Spring ApplicationContext, 可在任何地方getBean
|
|
13
|
+ */
|
|
14
|
+public class SpringContextHolder implements ApplicationContextAware {
|
|
15
|
+ private static ApplicationContext applicationContext;
|
|
16
|
+
|
|
17
|
+ /**
|
|
18
|
+ * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
|
|
19
|
+ */
|
|
20
|
+ @Override
|
|
21
|
+ public void setApplicationContext(ApplicationContext applicationContext) {
|
|
22
|
+ SpringContextHolder.applicationContext = applicationContext; // NOSONAR
|
|
23
|
+ }
|
|
24
|
+
|
|
25
|
+ /**
|
|
26
|
+ * 取得存储在静态变量中的ApplicationContext.
|
|
27
|
+ */
|
|
28
|
+ public static ApplicationContext getApplicationContext() {
|
|
29
|
+ checkApplicationContext();
|
|
30
|
+ return applicationContext;
|
|
31
|
+ }
|
|
32
|
+
|
|
33
|
+ public static <T> T getBean(String name) {
|
|
34
|
+ return (T) getApplicationContext().getBean(name);
|
|
35
|
+ }
|
|
36
|
+
|
|
37
|
+ public static <T> T getBean(Class<T> clazz) {
|
|
38
|
+ return (T) getApplicationContext().getBeansOfType(clazz);
|
|
39
|
+ }
|
|
40
|
+
|
|
41
|
+ public static <T> T getBean(Class<T> beanType, Class<? extends Annotation> annotationType) {
|
|
42
|
+ if (annotationType == null) {
|
|
43
|
+ return getBean(beanType);
|
|
44
|
+ }
|
|
45
|
+ Map<String, T> results = getApplicationContext().getBeansOfType(beanType);
|
|
46
|
+ List<T> resultsWithAnnotation = new ArrayList<T>();
|
|
47
|
+ for (Map.Entry<String, T> entry : results.entrySet()) {
|
|
48
|
+ if (getApplicationContext().findAnnotationOnBean(entry.getKey(), annotationType) != null) {
|
|
49
|
+ resultsWithAnnotation.add(entry.getValue());
|
|
50
|
+ }
|
|
51
|
+ }
|
|
52
|
+ if (resultsWithAnnotation.isEmpty()) {
|
|
53
|
+ return null;
|
|
54
|
+ }
|
|
55
|
+ if (resultsWithAnnotation.size() == 1) {
|
|
56
|
+ return resultsWithAnnotation.get(0);
|
|
57
|
+ }
|
|
58
|
+ throw new IllegalStateException("参数错误!未获取到对应Bean");
|
|
59
|
+ }
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+ private static void checkApplicationContext() {
|
|
63
|
+ if (applicationContext == null) {
|
|
64
|
+ throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
|
|
65
|
+ }
|
|
66
|
+ }
|
|
67
|
+
|
|
68
|
+}
|