package com.dmo.screen.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
//在普通的java类中获取Spring容器里面的对象
@SuppressWarnings("unchecked")
@Component
public class SpringUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
/**
* getBean
* @param beanName
* @return
*/
public static Object getBean(String beanName){
if(applicationContext.containsBean(beanName)){
return applicationContext.getBean(beanName);
}else{
return null;
}
}
public static Object getBean(Class requiredType){
isInjected();
return applicationContext.getBean(requiredType);
}
/**
* 判断是否注入
* @return
*/
public static void isInjected(){
if(SpringUtil.applicationContext == null){
throw new RuntimeException("springUtils applicationContext is not injected!");
}
}
}