spring中bean获取工具

如何通过静态方法的方式获取spring bean

package com.example.helper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Map;
/**
 * bean工具
 * @author xiaog
 * @Date 2021-04-06
 */
@Component
public class BeanHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("init applicationContext");
        BeanHelper.applicationContext = applicationContext;
    }

    /**
     * 通过beanName返回bean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return applicationContext != null ? applicationContext.getBean(beanName) : null;
    }

    /**
     * 通过bean class返回bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static<T> T getBean(Class<T> clazz) {
        return applicationContext != null ? applicationContext.getBean(clazz) : null;
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext != null ? applicationContext.getBean(beanName,clazz) : null;
    }

    public static <T> Collection<T> getBeans(Class<T> clazz) {
        return getBeansMap(clazz).values();
    }

    public static <T> Map<String,T> getBeansMap(Class<T> clazz) {
        return applicationContext != null ? applicationContext.getBeansOfType(clazz) : null;
    }

}
posted @ 2021-10-22 15:09  小小爬虫  阅读(69)  评论(0编辑  收藏  举报