有時候我們需要在一個類中使用已經被注入spring容器的類(比如被包掃描的mapper接口,或者加了@Component注解的類)
但一個類要想使用spring容器的對象,一般需要聲明對象,然後用@AutoWired注解,而這又要求目前類得被spring容器管理(被包掃描或者使用了@Component注解)
但我隻是想用一個接口,我不想讓目前類存入spring容器中,是以就有了标題的需求
是以可以使用下面的這個封裝類,調用get方法即可
![]() |
/**
* 從容器中擷取到bean對象
*/
@Component
public class SpringContainerUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext1) throws BeansException {
applicationContext=applicationContext1;
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
}
這個工具類的底層原理其實就是依托了springIOC的代碼
|