工具類篇-獲取Spring bean容器(ApplicationContext)

1、工具類定義

  1. 實現ApplicationContextAware,重寫接口中setApplicationContext方法獲取該對象。
  2. 將定義類歸於Spring容器管理(註解或xml配置)。
package com.company.base.utils;

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

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * 獲取Spring Bean容器-ApplicationContext
 */
@Component
public class SpringApplicationContextUtils implements ApplicationContextAware{
    private static ApplicationContext ap ;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ap = applicationContext;
    }

    /**
     * 根據註解類從容器獲取對象
     * @param annotationType 註解類
     * @return
     */
    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType){
        return ap.getBeansWithAnnotation(annotationType);
    }

    /**
     * 根據java class類型從容器中獲取對象
     * @param type 類型class
     * @param <T> 類型
     * @return
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> type){
        return ap.getBeansOfType(type);
    }

}

2、實例測試

Map<String, Object> controllerBeanMap= SpringApplicationContextUtils.getBeansWithAnnotation(Controller.class);
Iterator<Map.Entry<String, Object>> it = controllerBeanMap.entrySet().iterator();
while(it.hasNext()){
   Map.Entry<String, Object> entry = it.next();
   LOG.info(entry.getKey()+"=>"+entry.getValue());
}

LOG.info("------------getBeansOfType-----------");
//根據類型獲取(此處IBaseService爲接口)
Map<String, IBaseService> serviceBeanMap= SpringApplicationContextUtils.getBeansOfType(IBaseService.class);
Iterator<Map.Entry<String, IBaseService>> serviceBeanMapIt = serviceBeanMap.entrySet().iterator();
while(serviceBeanMapIt.hasNext()){
   Map.Entry<String, IBaseService> entry = serviceBeanMapIt.next();
   LOG.info(entry.getKey()+"=>"+entry.getValue());
}

輸出結果java

[ com.company.controller.DemoController : 36 ] - demoController=>com.company.controller.DemoController@53e5295b
[ com.company.controller.DemoController : 36 ] - fileController=>com.company.controller.FileController@4eb35d28
[ com.company.controller.DemoController : 36 ] - redisController=>com.company.controller.RedisController@2a0de107
[ com.company.controller.DemoController : 36 ] - userController=>com.company.controller.UserController@67b027ac
[ com.company.controller.DemoController : 39 ] - ------------getBeansOfType-----------
[ o.s.b.factory.support.DefaultListableBeanFactory : 251 ] - Returning cached instance of singleton bean 'userService'
[ com.company.controller.DemoController : 44 ] - userService=>com.company.service.UserService@40a74381

https://github.com/BAN-WANG/demogit

相關文章
相關標籤/搜索