在開發中,總是能碰到用注解注入不了Spring容器里面bean對象的問題。為了解決這個問題,我們需要一個工具類來直接獲取Spring容器中的bean。因此就寫了這個工具類,在此記錄一下,方便后續查閱。廢話不多說,直接上代碼。
一、代碼
package com.zxy.demo.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 獲取Spring容器中bean工具類
* @author ZENG.XIAO.YAN
* @date 2018年6月6日
*
*/
@Component("springContextUtils")
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanId) {
return (T) applicationContext.getBean(beanId);
}
public static <T> T getBean(Class<T> requiredType) {
return (T) applicationContext.getBean(requiredType);
}
/**
* Spring容器啟動后,會把 applicationContext 給自動注入進來,然后我們把 applicationContext 賦值到靜態變量中,方便后續拿到容器對象
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
}
x
1
package com.zxy.demo.spring;
2
3
import org.springframework.beans.BeansException;
4
import org.springframework.context.ApplicationContext;
5
import org.springframework.context.ApplicationContextAware;
6
import org.springframework.stereotype.Component;
7
8
/**
9
* 獲取Spring容器中bean工具類
10
* @author ZENG.XIAO.YAN
11
* @date 2018年6月6日
12
*
13
*/
14
"springContextUtils") (
15
public class SpringContextUtils implements ApplicationContextAware {
16
17
private static ApplicationContext applicationContext = null;
18
19
public static ApplicationContext getApplicationContext() {
20
return applicationContext;
21
}
22
23
("unchecked")
24
public static <T> T getBean(String beanId) {
25
return (T) applicationContext.getBean(beanId);
26
}
27
28
public static <T> T getBean(Class<T> requiredType) {
29
return (T) applicationContext.getBean(requiredType);
30
}
31
32
/**
33
* Spring容器啟動后,會把 applicationContext 給自動注入進來,然后我們把 applicationContext 賦值到靜態變量中,方便后續拿到容器對象
34
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
35
*/
36
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
37
SpringContextUtils.applicationContext = applicationContext;
38
}
39
40
}
二、用法
直接在代碼用調用
SpringContextUtils
靜態方法獲取bean就ok,可以通過bean的id獲取,也可以通過bean的類型獲取
RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
1
RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
三、注意事項
仔細看代碼可以發現我這個工具類上面加了個
@Component
注解。加這個注解的目的是為了把的
SpringContextUtils
的實例化交給Spring容器管理。當然,你也可以在xml中配置這個,我為了方便,直接用的注解。注意點:這個工具類的實例化必須由Spring容器來做