2020年11月30日

实现ApplicationContextAware获取Spring上下文中的Bean

点击数:0

package com.zhoujunwen;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    @SuppressWarnings(\"unchecked\")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    @SuppressWarnings(\"unchecked\")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException(\"applicaitonContext未注入,请在application-context.xml中定义SpringContextHolder\");
        }
    }

    public static void printAllBeans() {
        String[] beans = getApplicationContext().getBeanDefinitionNames();
        for (String beanName : beans) {
            Class<?> beanType = getApplicationContext().getType(beanName);
            System.out.println(\"BeanName:\" + beanName);
            System.out.println(\"Bean的类型:\" + beanType);
            System.out.println(\"Bean所在的包:\" + beanType.getPackage());
            System.out.println(\"Bean:\" + getApplicationContext().getBean(beanName));
        }
    }

}

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据