第一步:實現 ApplicationContextAware接口
第二步:給類加上註解 @Component 讓spring識別並且注入
第三步:定義好靜態的 ApplicationContext ,在ApplicationContextAware實現的 setApplicationContext賦值過去;
後面就是自己根據自己的需求定義獲取bean的接口
如:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Created by Lee on 2018/5/7.
*/
@Component
public class DemoApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("我已經注入啦");
context=applicationContext;
}
public static <T> T getBean(Class<T> tClass){
if(null==context){
return null;
}
return context.getBean(tClass);
}
}
注:如果項目啓動後ApplicationContext爲空的話,可能是項目配置了全局spring bean的懶加載功能,這時候就需要在類上加個註解: @Lazy(value=false)