Fork me on GitHub

【11-10】spring学习笔记-ApplicationContextAware

package util;

/** 
* @author aloha_world_ 
* @date 2016年11月10日 下午7:50:08 
* @version v1.00
* @description
*/
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 实现 ApplicationContextAware方法Spring会在启动时自动注入SpringContext,程序中可以直接调用该类的静态方法获取bean
 *
 */
@Component
public class MyApplicationContext implements ApplicationContextAware {
	public static ApplicationContext context;

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		MyApplicationContext.context = context;
	}

	public static <T> T getBean(Class<T> clazz) {
		return (T) context.getBean(clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		return (T) context.getBean(beanName);
	}

}
posted @ 2016-11-10 19:54  aloha_world  阅读(105)  评论(0编辑  收藏  举报