【Spring】ApplicationContextAware

ApplicationContextAware

ApplicationContextAware是org.springframework.context中提供的接口,接口只有一个方法setApplicationContext。

package org.springframework.context;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;public interface ApplicationContextAware extends Aware {void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

ApplicationContextAware用法

当一个类实现了这个接口之后,这个类就可以方便的获得ApplicationContext对象(spring上下文),Spring发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContext(参数)方法,调用该方法时会将容器本身ApplicationContext对象作为参数传递给该方法。
拿到ApplicationContext对象后就可以使用其做一些事情,比如获取Bean对象,下列简单的封装了一个工具类:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;/*** ApplicationContextUtil* @author CK*/
@Component
public class ApplicationContextUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;/*** 自动加载ICO容器对象,该方法在启动项目是会自动执行* @param applicationContext* @throws BeansException*/@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}/*** 通过name获取Bean* @param name* @return*/public static Object getBean(String name){return applicationContext.getBean(name);}/*** 通过class获取Bean* @param var* @return* @param */public static <T> T getBean(Class<T> var){return applicationContext.getBean(var);}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部