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
package cn.wisenergy.common.utils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component("springUtils")
@Lazy(false)
public final class SpringUtils implements ApplicationContextAware,
DisposableBean {
/**
* applicationContext
*/
private static ApplicationContext applicationContext;
/**
* 不可实例化
*/
private SpringUtils() {
}
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtils.applicationContext = applicationContext;
}
public void destroy() throws Exception {
applicationContext = null;
}
/**
* 获取applicationContext
*
* @return applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取实例
*
* @param name
* Bean名称
* @return 实例
*/
@SuppressWarnings("deprecation")
public static Object getBean(String name) {
Assert.hasText(name);
return applicationContext.getBean(name);
}
/**
* 获取实例
*
* @param name
* Bean名称
* @param type
* Bean类型
* @return 实例
*/
@SuppressWarnings("deprecation")
public static <T> T getBean(String name, Class<T> type) {
Assert.hasText(name);
Assert.notNull(type);
return applicationContext.getBean(name, type);
}
}