簡介
spring在創(chuàng)建當(dāng)前bean時,會去調(diào)用ApplicationContextAware接口的擴(kuò)展點(diǎn),ApplicationContextAware有個方法setApplicationContext贺奠。
實(shí)現(xiàn)ApplicationContextAware接口名扛,可以獲取到Spring的ApplicationContext上下文對象。ApplicationContext上下文繼承了BeanFactory, 因而可以從上下文對象獲取指定bean辩恼。如果該bean尚未創(chuàng)建惕橙,會觸發(fā)bean的創(chuàng)建流程篮绿,功能跟BeanFactoryAware相同。
示例
@Service
public class BeanFactoryUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
Objects.requireNonNull(beanName, "beanName不能為空!");
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> requiredType) {
Objects.requireNonNull(requiredType, "requiredType不能為空!");
return (T) applicationContext.getBean(requiredType);
}
public <T> Collection<T> getBeanList(Class<T> requiredType) {
return MapUtils.emptyIfNull(applicationContext.getBeansOfType(requiredType)).values();
}
}