获取SpringBean对象工具类

编程

# 获取SpringBean工具类

SpringBeanUtil代码如下:

package com.meeno.wzq.util;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.stereotype.Component;

/**

 * @description: SpringBeanUtil

 * @author: Wzq

 * @create: 2019-10-08 16:24

 */

@Component

//实现Spring Bean生命周期接口ApplicationContextAware

public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        if(SpringBeanUtil.applicationContext == null) {

            SpringBeanUtil.applicationContext = applicationContext;

        }

        System.out.println("---------------------------------------------------------------------");

        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringBeanUtil.applicationContext+"========");

        System.out.println("---------------------------------------------------------------------");

    }

    //获取applicationContext

    public static ApplicationContext getApplicationContext() {

        return applicationContext;

    }

    //通过name获取 Bean.

    public static Object getBean(String name){

        return getApplicationContext().getBean(name);

    }

    //通过class获取Bean.

&nbsp; &nbsp; public static <t> T getBean(Class<t> clazz){

&nbsp; &nbsp; &nbsp; &nbsp; return getApplicationContext().getBean(clazz);

&nbsp; &nbsp; }

&nbsp; &nbsp; //通过name,以及Clazz返回指定的Bean

&nbsp; &nbsp; public static <t> T getBean(String name,Class<t> clazz){

&nbsp; &nbsp; &nbsp; &nbsp; return getApplicationContext().getBean(name, clazz);

&nbsp; &nbsp; }

}

个人微信公众,经常更新一些实用的干货:

![image.png](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91cGxvYWQtaW1hZ2VzLmppYW5zaHUuaW8vdXBsb2FkX2ltYWdlcy8xODU1NzgxMy00YzkyNzUzY2NhNDY1ZGZjLnBuZw?x-oss-process=image/format,png)

最后加上高质量的淘宝店:如有质量问题随时滴滴我,童叟无欺!

![微信图片_20191111194455.png](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91cGxvYWQtaW1hZ2VzLmppYW5zaHUuaW8vdXBsb2FkX2ltYWdlcy8xODU1NzgxMy1iZjlkMjQzYjg5OWIyYTA1LnBuZw?x-oss-process=image/format,png)</t></t></t></t>

以上是 获取SpringBean对象工具类 的全部内容, 来源链接: utcz.com/z/511699.html

回到顶部