不需要spring管理,自己根据名字取到对应的bean

package com.yiban.abc.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Configuration;

import java.util.Map;


@Configuration
public class SpringBeanUtil implements BeanFactoryAware {
    private static BeanFactory beanFactory;
    private static DefaultListableBeanFactory listtableBeanFactory;

    public SpringBeanUtil() {
    }

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        SpringBeanUtil.beanFactory = beanFactory;
        listtableBeanFactory = (DefaultListableBeanFactory)beanFactory;
    }

    public static Object getBean(String name) throws BeansException {
        return beanFactory.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return beanFactory.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return beanFactory.getBean(name, requiredType);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> requiredType) throws BeansException {
        return listtableBeanFactory.getBeansOfType(requiredType);
    }
}

 

posted @ 2019-10-10 13:48  xiaowejie  阅读(363)  评论(0编辑  收藏  举报