Spring源码学习--从Springboot的ApplicationContext获取Bean

 2019-10-17 21:52  阅读(2120)
文章分类:Spring boot

某些类A无法注入的情况下,需要用到其他被Spring注入的对象B,此时在A类如果想使用B,可以采取下面的方式

import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;

    /** * Description:获取bean工具 * * @author DemoTransfer * @date 2018年5月19日 下午1:42:56 */
    public class SpringBeanUtil {

        private static ApplicationContext applicationContext;
        static final private Object lock = new Object();

        /** * 设置上下文 * * @param applicationContext * @throws BeansException */
        public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            synchronized (lock) {
                if (SpringBeanUtil.applicationContext == null) {
                    SpringBeanUtil.applicationContext = applicationContext;
                }
            }
        }

        /** * 获取applicationContext * * @return */
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }

        /** * 通过name获取 Bean * * @param name * @return */
        public static Object getBean(String name) {
            return getApplicationContext().getBean(name);
        }

        /** * 通过class获取Bean * * @param clazz * @return */
        public static <T> T getBean(Class<T> clazz) {
            return getApplicationContext().getBean(clazz);
        }

        /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @return */
        public static <T> T getBean(String name, Class<T> clazz) {
            return getApplicationContext().getBean(name, clazz);
        }
    }

设置ApplicationContext地方

import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ConfigurableApplicationContext;

    @SpringBootApplication
    public class WebApplication {

        private static ApplicationContext applicationContext;

        public static void main(String[] args) {
            applicationContext = SpringApplication.run(WebApplication.class, args);
            SpringBeanUtil.setApplicationContext(applicationContext);
        }

    }

使用场景

UnInstallServiceImpl unInstallServiceImpl = (UnInstallServiceImpl) SpringBeanUtil.getBean("unInstallService");

来源:[]()

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Spring源码学习--从Springboot的ApplicationContext获取Bean

相关推荐