ludc
2025-01-16 5203081b68e3a8dc139d1807b2f8774e4a00a82a
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
package com.vci.starter.web.util;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
/**
 * spring的上下文工具,
 * @author dangsn
 * @date 2024/12/3
 */
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
 
    /**
     * 应用的上下文
     */
    private static ApplicationContext applicationContext ;
 
    /**
     * 设置应用的上下文
     * @param context 上下文
     * @throws BeansException 出现错误时需要抛出异常给spring容器
     */
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
 
    /**
     * 获取应用的上下文
     * @return 上下文
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
    /**
     * 获取对象
     * @param name bean的名称
     * @return Object bean的对象
     * @throws BeansException 如果不存在会抛出异常
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
 
    /**
     * 获取对象
     * @param c bean的接口类
     * @param <T> bean所属类的类型
     * @return bean对象
     * @throws BeansException 如果不存在会抛出异常
     */
    public static <T> T getBean(Class<T> c) throws BeansException{
        return applicationContext.getBean(c);
    }
}