Springboot动态获取bean对象工具类

 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 }

/** * ApplicationContextProvider * * @author shenhelin * @date 2019-07-04 **/@Componentpublic class ApplicationContextProvider implements ApplicationContextAware {
    /**     * 上下文对象实例     */    private static ApplicationContext applicationContext;
    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        ApplicationContextProvider.applicationContext = applicationContext;    }
    /**     * 获取Spring上下文     *     * @return     */    public static ApplicationContext getApplicationContext() {        return applicationContext;    }
    /**     * 通过name获取Bean     *     * @param name     * @return     */    public static Object getBean(String name) {        return getApplicationContext().getBean(name);    }
    /**     * 通过class获取Bean     *     * @param clazz     * @param <T>     * @return     */    public static <T> T getBean(Class<T> clazz) {        return getApplicationContext().getBean(clazz);    }
    /**     * 通过name,以及Clazz返回指定的Bean     *     * @param name     * @param clazz     * @param <T>     * @return     */    public static <T> T getBean(String name, Class<T> clazz) {        return getApplicationContext().getBean(name, clazz);    }
}

猜你喜欢

转载自www.cnblogs.com/alex-xyl/p/12463300.html