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
package com.java110.utils.factory;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
 
/**
 * Created by wuxw on 2017/4/25.
 */
 
public class ApplicationContextFactory {
 
    private static ApplicationContext applicationContext;
 
    public static void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        ApplicationContextFactory.applicationContext = applicationContext;
    }
 
    public static Object getBean(Class className){
        return applicationContext.getBean(className);
    }
 
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }
 
    public static <T> T getBean(String beanName,Class<T> t){
        Object bean = applicationContext.getBean(beanName);
 
        if(bean != null && t.isAssignableFrom(bean.getClass()) ){
            return (T)bean;
        }
 
        return null;
    }
}