#
18516761980
2021-08-16 f25c800bca726b67ea74e6ed576b038b1b9561a7
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
66
67
68
69
70
71
72
73
74
75
76
77
package com.slcf.util;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
 
/**
 * 获取Spring容器中Bean实例的工具类(Java泛型方法实现)。
 *
 * @author leiwen@FansUnion.cn
 */
@Service
public class SpringBeanUtils implements BeanFactoryAware {
 
    private static BeanFactory beanFactory;
 
    /**
     * 注入BeanFactory实例
     */
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        SpringBeanUtils.beanFactory = beanFactory;
    }
 
    /**
     * 根据bean的名称获取相应类型的对象
     *
     * @param beanName
     *            bean的名称
     * @return Object类型的对象
     */
    public static Object getBean(String beanName) {
        return beanFactory.getBean(beanName);
    }
 
    /**
     * 根据bean的类型获取相应类型的对象,没有使用泛型,获得结果后,需要强制转换为相应的类型
     *
     * @param clazz
     *            bean的类型,没有使用泛型
     * @return Object类型的对象
     */
    public static Object getBean(Class clazz) {
        WebApplicationContext wac = ContextLoader
                .getCurrentWebApplicationContext();
        Object bean = wac.getBean(clazz);
        return bean;
    }
 
    /**
     * 根据bean的名称获取相应类型的对象,使用泛型,获得结果后,不需要强制转换为相应的类型
     *
     * @param clazz
     *            bean的类型,使用泛型
     * @return T类型的对象
     */
    public static <T> T getBean2(Class<T> clazz) {
        WebApplicationContext wac = ContextLoader
                .getCurrentWebApplicationContext();
        T bean = wac.getBean(clazz);
        return bean;
    }
 
    // 用法演示
    public static void main() {
        // 需要强制转换,不够便捷
//        Class o1 = (Class) SpringBeanUtils.getBean2(Class.class);
 
        // 需要强制转换,不够便捷
//        User user = (User) SpringBeanUtils.getBean("user");
 
        // 不用强制转换--推荐使用
//        User user2 = SpringBeanUtils.getBean2(User.class);
    }
}