1、实现ApplicationContextAware接口
package com.caiya.test.springboot.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 获取spring上下文、spring管理的bean对象的工具类
* Created by caiya on 16/8/28.
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据bean的name来查找对象
*
* @param name
* @return
*/
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
/**
* 根据bean的class来查找对象
*
* @param clazz
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
/**
* 根据bean的class来查找所有的对象(包括子类)
*
* @param clazz
* @return
*/
public static <T> Map<String, T> getBeans(Class<T> clazz) {
return applicationContext.getBeansOfType(clazz);
}
}