Spring上下文对象

接上一篇,如果没有Servlet代理类,而又想在Servlet(或其他非同一Spring容器管理的对象)中获取目标bean,可以实现接口org.springframework.context.ApplicationContextAware,然后将实现类作为bean,然后可以正常使用,一般是将常用的getBean、getBeansOfType等包装成类方法,一是方便作为工具方法调用,二来可以自己捕获异常,再抛出项目中的指定异常。实际上,ApplicationContextAware的类型层次结构中,有一个实现类org.springframework.context.support.ApplicationObjectSupport,并整合了MessageSourceAccessor很方便。代码如下:


package com.xxx.context;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;

import xxx.xxx.BusinessException;


/**
 *  Spring上下文

**/
public class SpringContext extends ApplicationObjectSupport implements InitializingBean {

 /** 当前上下文 */
 private static ApplicationContext context = null;
 /** 消息存取器 */
 private static MessageSourceAccessor messageSourceAccessor = null;


 @Override
 public void afterPropertiesSet() throws Exception {
  context = super.getApplicationContext();
  messageSourceAccessor = new MessageSourceAccessor(context);
  Assert.notNull(context, "ApplicationContext不能为空!");
  Assert.notNull(messageSourceAccessor, "messageSourceAccessor不能为空!");
 }


 /**
  * 根据名称获取Bean
  *
  * @param beanName
  * @return
  */
 public static Object getBean(String beanName) throws BusinessException {
  try {
   return context.getBean(beanName);
  }
  catch (Exception e) {
   throw new BusinessException("", e);
  }
 }


 /**
  * 根据类型获取Bean Map
  *
  * @param type
  * @return
  */
 public static Map getBeanMapOfType(Class type) throws BusinessException {
  try {
   return context.getBeansOfType(type);
  }
  catch (Exception e) {
   throw new BusinessException("", e);
  }
 }


 /**
  * 根据类型获取Bean List
  *
  * @param type
  * @return
  */
 public static List getBeanListOfType(Class type) throws BusinessException {
  Map beanMap = getBeanMapOfType(type);
  List list = new ArrayList();
  if (MapUtils.isNotEmpty(beanMap)) {
   list.addAll(beanMap.values());
  }
  return list;
 }


 /**
  * 根据类型获取Bean Array
  *
  * @param type
  * @return
  */
 public static T[] getBeanArrayOfType(Class type) throws BusinessException {
  List list = getBeanListOfType(type);
  @SuppressWarnings("unchecked")
  T[] array = (T[]) Array.newInstance(type, list.size());
  array = list.toArray(array);
  return array;
 }


 /**
  * 获取国际化消息
  *
  * @param code
  *              消息代码
  * @return
  */
 public static String getMessage(String code) throws BusinessException {
  try {
   return messageSourceAccessor.getMessage(code);
  }
  catch (Exception e) {
   throw new BusinessException("", e);
  }
 }

}

 

你可能感兴趣的:(Spring,Spring)