java110
2021-05-15 811e8e7139ad6e331c2f84bcd5cf3f927a8b3312
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.java110.utils.factory;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
 
import java.util.Locale;
 
/**
 * 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;
    }
 
    /**
     * 获取应用名称
     * @return
     */
    public static String getApplicationName(){
        return applicationContext.getEnvironment().getProperty("spring.application.name");
    }
 
 
    // 国际化使用
    public static String getMessage(String key) {
        return applicationContext.getMessage(key, null, Locale.getDefault());
    }
 
 
    /// 获取当前环境
    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }
 
 
}