zoukankan      html  css  js  c++  java
  • springboot中有用的几个有用aware以及bean操作和数据源操作

    本文参考了:

    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); } } }
  • 相关阅读:
    python+requests+excel 接口测试
    Pycharm配置git
    ubuntu16.04+ROS安装kinectV1
    ubuntu16.04安装有道词典
    ROS kinetic语音识别
    在Ubuntu16.04中python环境下实现tab键补全
    ros kinetic安装rbx1
    ubuntu14.04安装opencv3.1
    ubuntu16.04SSH无法连接
    VC6中函数点go to definition报告the symbol XXX is undefined
  • 原文地址:https://www.cnblogs.com/lzfhope/p/9821749.html
Copyright © 2011-2022 走看看