• 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); } } }
  • 相关阅读:
    有一种尺度叫圆融
    十大经典排序算法
    Maximal Square
    Word Break
    Flatten List
    Triangle
    Paint Fence
    Longest Increasing Continuous Subsequence
    Minimum Size Subarray Sum
    Letter Combinations of a Phone Number
  • 原文地址:https://www.cnblogs.com/lzfhope/p/9821749.html
Copyright © 2020-2023  润新知