首页 > 移动平台 > 详细

ApplicationContextAware接口认识

时间:2021-09-03 21:30:31      阅读:18      评论:0      收藏:0      [点我收藏+]

今天用到公司的工具类有个获取Spring容器bean的方法,点开看了下源码,发现只是实现类ApplicationContextAware, EmbeddedValueResolverAware两个接口

继承ApplicationContextAware接口会重写setApplicationContext方法,该方法在启动时会自动执行,前提时该类也属于IOC容器,比如有@Component注解,

执行后可以拿到框架加载的Ioc容器。

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringHelper.applicationContext = applicationContext;
    }

 

 简单来说,这个接口就是用来获取自动初始化的ioc容器对象的;

看下源码:

package com.lyq.utils;

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

@Component
public class SpringHelper implements ApplicationContextAware, EmbeddedValueResolverAware {
    //静态ApplicationContext
    private static ApplicationContext applicationContext;
    private static StringValueResolver valueResolver;

    public SpringHelper(){}
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        /** 将框架初始化加载的ioc容器赋值给 静态ApplicationContext*/
        SpringHelper.applicationContext = applicationContext;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {

    }
    //获取Ioc容器
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    //通过class获取Bean
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }
    //通过名称获取Bean
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过名称、class获取Bean
    public static <T> T getBean(Class<T> clazz, String name){
        return getApplicationContext().getBean(name, clazz);
    }

}

 

ApplicationContextAware接口认识

原文:https://www.cnblogs.com/omgliyq/p/15221475.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!