spingboot获得ioc容器

本博客参考链接

https://www.cnblogs.com/nongzihong/p/11350308.html

我的工具类

package com.iot.donation.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author 张满
 * @Description 获得ApplicationContext
 * @Date 2020/1/1 0:08
 * @vsersion 1.0.0
 **/
@Component
public final class SpringUtils implements ApplicationContextAware, InitializingBean {

    private static ApplicationContext applicationContext;


    /**
     * @Author 张满
     * @Description 启动时获得spring容器
     * @Date 2020/1/1  14:43
     * @Param [applicationContext]
     * @return void
     **/
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringUtils.applicationContext = applicationContext;
    }


    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static Object getBean(String beanName){
        return getApplicationContext().getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }


    /**
     * @Author 张满
     * @Description 打印ioc容器中所有bean名称
     * @Date 2020/1/1  14:34
     * @Param []
     * @return void
     **/
    @Override
    public void afterPropertiesSet() throws Exception {
//        String[] names = applicationContext.getBeanDefinitionNames();
//        for (String name : names) {
//            System.out.println(">>>>>>>>>>>>>>>>>>"+name);
//        }
//        System.out.println("<<<<<<<<<<<<
    }
}

使用

AlumniService alumniService = SpringUtils.getBean(AlumniServiceImpl.class);

你可能感兴趣的:(心得总结)