关于Spring中ApplicationContext加载机制中BeanFactory类

来源:互联网 发布:网络视频推广方案 编辑:程序博客网 时间:2024/05/21 17:29

   最近看到使用的BeanFactory是关于Spring中ApplicationContext加载机制的,同时深入地查看了BeanFactory

类.

package com.chinasofti.whb.util.util;

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

public class BeanFactory implements ApplicationContextAware {

// Spring应用上下文环境
private static ApplicationContext applicationContext;

/**
* 实现ApplicationAware接口的回调方法,设置上下文环境
*
* @param application
*/
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
// BeanFactory.applicationContext = applicationContext;
this.applicationContext = applicationContext;
}

/**
* return applicationContext
*/
public static ApplicationContext getApplicationContext() {

return applicationContext;

}

/**
* 获取对象
*
* @param name
* @return Object
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
checkApplication();
return applicationContext.getBean(name);

}

/**
* 获取对象
*
* @param name
* @param requiretype
* @return Object
* @author BeansException
*/
public static Object getBObject(String name, Class requiretype)
throws BeansException {
checkApplication();
return applicationContext.getBean(name, requiretype);
}

public static void cleanApplication() {
applicationContext = null;
}

/**
* 检查spring注入
*/
public static void checkApplication() {
if (applicationContext == null) {
throw new IllegalStateException("Spring未注入,请在配置文件中注入");
}
}
}

0 0
原创粉丝点击