天天看點

SpringBoot--靜态獲得Bean的工具類(基于ApplicationContext)

簡介

說明

        本文提供一個靜态獲得Bean的工具類。

        可以通過本工具類靜态擷取ApplicationContext,進而進一步使用ApplicationContext進行處理,比如:從容器中擷取bean。

優點

代碼

package com.knife.common.util;

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

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextHolder.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}      

用法

  • 根據class獲得bean(常用)
  • Xxx xxx = ApplicationContextHolder.getContext().getBean(Xxx.class);
  • 根據名字獲得代理後的bean(常用)
  • Xxx xxx = ApplicationContextHolder.getContext().getBean("userService");
  • 根據名字獲得未代理的bean(即FactoryBean)(不常用)
  • Xxx xxx = ApplicationContextHolder.getContext().getBean("&userService");