SpringBoot中static方法中使用Autowired

有时候我们需要在static公共方法中使用@Autowired,

解决方案:

使用 applicationContext.getBean(BaseBizClient.class)的方法

  1. 获取Util的instance,单例模式
1
2
3
4
5
6
7
//线程安全 懒汉单例
public static synchronized DealerGetUtil getInstance() {
if (null == instance) {
instance = new DealerGetUtil();
}
return instance;
}
  1. 获取 applicationContext
1
2
3
4
5
6
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (DealerGetUtil.applicationContext == null) {
DealerGetUtil.applicationContext = applicationContext; //初始化 spring applicationContext
}
}
  1. 创建获取Bean方法:
1
2
3
4
5
6
7
//注入对象BaseBizClient
private synchronized BaseBizClient getBaseBizClient() {
if (baseBizClient == null) {
baseBizClient = applicationContext.getBean(BaseBizClient.class);
}
return baseBizClient;
}

完整代码

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
/**
* Created by Youdmeng on 2018/7/17 0017.
*/
@Component
@EnableFeignClients
public class DealerGetUtil implements ApplicationContextAware {

private static ApplicationContext applicationContext = null;

private BaseBizClient baseBizClient;

private static DealerGetUtil instance;

private DealerGetUtil() {
}

//线程安全 懒汉单例
public static synchronized DealerGetUtil getInstance() {
if (null == instance) {
instance = new DealerGetUtil();
}
return instance;
}

/**
*
* @param userVO
* @return
* @throws Exception
*/
public String getDealer(UserVO userVO) throws Exception {
String dealerId = "";
//获取员工
UserPageResponseVO userPageResponseVO = getBaseBizClient().getUser(SysConstant.SYSTEM.toString(), userVO.getUserId()).getData();

return "";
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (DealerGetUtil.applicationContext == null) {
DealerGetUtil.applicationContext = applicationContext; //初始化 spring applicationContext
}
}

//注入对象BaseBizClient
private synchronized BaseBizClient getBaseBizClient() {
if (baseBizClient == null) {
baseBizClient = applicationContext.getBean(BaseBizClient.class);
}
return baseBizClient;

}





更多好玩好看的内容,欢迎到我的博客交流,共同进步        胡萝卜啵的博客