ApplicationContextAware简单用法

timo-nbktp 1年前 ⋅ 827 阅读

ApplicationContextAware用法

当一个类实现了这个接口之后,这个类就可以方便的获得ApplicationContext对象(spring上下文),Spring发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContext(参数)方法,调用该方法时,会将容器本身ApplicationContext对象作为参数传递给该方法。

package com.lyj.demo.utils;

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


@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static ApplicationContext getApplicationContext(){
        return context;
    }
    /**
     * 通过name获取 Bean
     * @param name beanName
     * @return Object
     */
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }



    public static <T> T getBean(Class<T> requiredType) throws BeansException{
        return getApplicationContext().getBean(requiredType);
    }
}


 

 

 

-----end------

 

 

 

版权 本着开源共享、共同学习的精神,本文转载自 https://blog.csdn.net/qq_40093255/article/details/117318760 , 如果侵权之处,请联系博主进行删除,谢谢~