jinpengyong
2021-08-09 d6c509ab43bd472e56e3d9a9ddde0b335b7fd67e
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
package com.moral.util;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
 
import java.lang.annotation.Annotation;
import java.util.Map;
 
 
public class SpringContextUtils {
 
    private static ApplicationContext applicationContext;
 
    public SpringContextUtils() {
    }
 
    /**
     * 获取applicationContext对象
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
 
    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }
 
 
    /**
     * 根据 bean 的 name 来查找对象
     *
     * @param beanName bean name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBeanByName(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }
 
 
    /**
     * 根据 bean 的 类型 来查找对象
     *
     * @param requiredType
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBeanByClass(Class<?> requiredType) {
        return (T) applicationContext.getBean(requiredType);
    }
 
    public static <T> Map<String, T> getBeansByClass(Class<T> cls) {
        return applicationContext.getBeansOfType(cls);
    }
 
    public static Map<String, Object> getBeansByAnnotation(Class<? extends Annotation> annotationCls) {
        return applicationContext.getBeansWithAnnotation(annotationCls);
    }
 
}