SpringBeanUtitl.java
1.4 KB
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
package com.sunyo.wlpt.message.builder.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @ProjectName:
* @Package: com.backstage.config
* @ClassName: ApplicationContextProvider
* @Description: 获取bean对象的工具类
* @Author: wangzhilong
* @CreateDate: 2018/8/31 13:26
* @Version: 1.0
*/
/**
* Author:ZhuShangJin
* Date:2018/7/3
*/
@Component
public class SpringBeanUtitl implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
// TODO Auto-generated method stub
SpringBeanUtitl.applicationContext = applicationContext;
}
/**
* 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
if(name == null || applicationContext == null){
return null;
}
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}