86183
2022-09-09 0d999e33085c0a25c5525242748f6aa62a401159
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
package com.dsh.utils;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
 
/**
 * * @author: lihong .
 * * @email: 765907456@qq.com .
 * * @createTime:  19-7-15 上午11:14 .
 * * description: api方式获取bean.
 **/
@Component
public class SpringBeanUtils implements ApplicationContextAware {
    private static ApplicationContext APPLICATION_CONTEXT;
 
    /**
     * 根据名称获取Bean
     *
     * @param beanName
     * @return
     */
    public static <T> T getBean(String beanName) {
        Assert.hasText(beanName, "获取bean名称不能为空.");
        if (APPLICATION_CONTEXT.containsBean(beanName)) {
            return (T) APPLICATION_CONTEXT.getBean(beanName);
        }
        return null;
    }
 
    /**
     * 根据类型获取bean
     *
     * @param targetType
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> targetType) {
        Assert.notNull(targetType, "目标类型不能为空.");
        return APPLICATION_CONTEXT.getBean(targetType);
    }
 
    /**
     * 根据类型名称获取bean
     *
     * @param beanName
     * @param targetType
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> targetType) {
        Assert.notNull(targetType, "目标类型不能为空");
        Assert.hasText(beanName, "bean名称不能为空.");
        if (APPLICATION_CONTEXT.containsBean(beanName)) {
            return APPLICATION_CONTEXT.getBean(beanName, targetType);
        }
        return null;
 
    }
 
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtils.APPLICATION_CONTEXT = applicationContext;
    }
}