码迷,mamicode.com
首页 > 编程语言 > 详细

springboot中有用的几个有用aware以及bean操作和数据源操作

时间:2018-10-20 16:30:05      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:.net   throw   log   contex   操作   public   上线   str   dsc   

本文参考了:

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); } } }

 

springboot中有用的几个有用aware以及bean操作和数据源操作

标签:.net   throw   log   contex   操作   public   上线   str   dsc   

原文地址:https://www.cnblogs.com/lzfhope/p/9821749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!