1. 程式人生 > >springboot中有用的幾個有用aware以及bean操作和數據源操作

springboot中有用的幾個有用aware以及bean操作和數據源操作

pub art exception private exce 數據源 static ini sco

本文參考了:

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操作和數據源操作