1 /**
 2  * ApplicationContextProvider
 3  * 5  * @date 2019-07-04
 6  **/
 7 @Component
 8 public class ApplicationContextProvider implements ApplicationContextAware {
 9 
10     /**
11      * 上下文对象实例
12      */
13     private static ApplicationContext applicationContext;
14 
15     @Override
16     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
17         ApplicationContextProvider.applicationContext = applicationContext;
18     }
19 
20     /**
21      * 获取Spring上下文
22      *
23      * @return
24      */
25     public static ApplicationContext getApplicationContext() {
26         return applicationContext;
27     }
28 
29     /**
30      * 通过name获取Bean
31      *
32      * @param name
33      * @return
34      */
35     public static Object getBean(String name) {
36         return getApplicationContext().getBean(name);
37     }
38 
39     /**
40      * 通过class获取Bean
41      *
42      * @param clazz
43      * @param <T>
44      * @return
45      */
46     public static <T> T getBean(Class<T> clazz) {
47         return getApplicationContext().getBean(clazz);
48     }
49 
50     /**
51      * 通过name,以及Clazz返回指定的Bean
52      *
53      * @param name
54      * @param clazz
55      * @param <T>
56      * @return
57      */
58     public static <T> T getBean(String name, Class<T> clazz) {
59         return getApplicationContext().getBean(name, clazz);
60     }
61 
62 }


 

posted on 2020-03-11 16:36  Alex-XYL  阅读(6136)  评论(0编辑  收藏  举报