1. 程式人生 > >springboot普通類呼叫spring託管的類,使用參照註釋中用例

springboot普通類呼叫spring託管的類,使用參照註釋中用例

package com.prodaas.datatools.batchplatform.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 使用該類建立直接與資料庫互動的service物件
 * 用例:ApplicationContext applicationContext = SpringHelper.getApplicationContext();
 *      StandardInfoService service = applicationContext.getBean(StandardInfoService.class);
 *      ArrayList<String[]> detailValues =(ArrayList)service.getRulesTable(f.getStdSortId());
 */
@Component
public class SpringHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringHelper.applicationContext == null){
            SpringHelper.applicationContext  = applicationContext;
        }
    }


    //獲取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通過name獲取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通過class獲取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通過name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

}