一、工具类定义
- 实现ApplicationContextAware,重写接口中setApplicationContext方法获取该对象。
- 将定义类归于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);
}
}
二、实例测试
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());
}
输出结果
[ 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/demo