本文参考了:
https://blog.csdn.net/derrantcm/article/details/76652951
https://blog.csdn.net/derrantcm/article/details/73456550
通过以上可以获得springboot的许多知识。
本文只是列出本人常用的两个aware.
闲话少叙,直接上代码
BeanFactoryAware 帮助获取各种bean
import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.stereotype.Component; @Component public class BeanHelper implements BeanFactoryAware { private static BeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public static <T>T getBean(String id,Class<T> type){ return beanFactory.getBean(id,type); } public static <T>T getBean(Class<T> type){ return beanFactory.getBean(type); } public static <T>T getBean(String beanName){ return (T) beanFactory.getBean(beanName); } }
ApplicationContextAware 帮助获取上线文的信息,也可以操作bean
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class DsControl implements ApplicationContextAware { @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//dataSource在springboot中是一个关键字 Object ds=applicationContext.getBean("dataSource") ; System.out.println("当前的连接池是:"+ds.getClass().getName()); System.out.println("-----gooooo"); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { System.out.println(beanDefinitionName); } } }