获取springbean的几种方式

首先我说一下我遇到的问题,再项目初始化时候,spring容器初始化前要执行的操作中使用到了bean去做一些增删改查操作,这样做是不能自己使用springbean的数据源去操作的,所以需要动态获取springbean,又不想重新封装jdbc数据源去操作,,可以直接获取到spring配置文件中的数据源进行操作

第一种方法是

在初始化时保存ApplicationContext对象
代码:
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。

//但是我不明白怎么去配置初始化spring,我写的时候 new FileSystemXmlApplicationContext("applicationContext.xml");返回的不是ApplicationContext,所以pass掉了,,还需要再学习一下

鬼使神差的又可以了,,, ApplicationContext ac = new FileSystemXmlApplicationContext("app-persistence.xml");可以拿到了哦各位

 

方法二:通过Spring提供的工具类获取ApplicationContext对象
代码:
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

方法三:继承自抽象类ApplicationObjectSupport
说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。
Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport
说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

方法五:实现接口ApplicationContextAware
说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
Spring初始化时,会通过该方法将ApplicationContext对象注入。

 

 

最后说一下我所使用的是第五种方式,该方法实现ApplicationContextAware接口,然后直接通过上下文就可以获取配置文件中的bean,

注意:该方法不以来servlet,不需要注入的方式,在服务器启动时,Spring容器初始化时,不能通过以下方法获取Spring 容器。

  WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();    

  wac.getBean("");    

 

直接上代码

@Service
public class BlhRequestExecutor
  extends AbstractRequestExecutor implements ApplicationContextAware
{
    private Logger logger = LoggerFactory.getLogger(BlhRequestExecutor.class);
    private static ApplicationContext context = null; 
  public BlhRequestExecutor() {}
  
  public IZrarResponse service(HttpServletRequest request, HttpServletResponse response) throws BaseException {
	  IZrarRequest zrarRequest = new ZrarRequest(request);
	  IBaseZrarDao dao  = (IBaseZrarDao) context.getBean("dao");
	  //记录日志实体
	  System.out.println("----------------------------------记录日志开始---------------");
	  String id = IdGenerator.getGuid();
	  String commite =null;
	  String endTime =null;
	  String usedTime =null;
	  long end;
	  long start; 
		//获取系统时间
      String startTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
      start = System.currentTimeMillis();
		//获取登陆用户账户
		String userId = LoginCtrlSession.getYhid();
		System.out.println(userId);
		String userName = LoginCtrlSession.getYhmc();
		String visitUrl = String.valueOf(request.getRequestURL().toString());
      System.out.println("----------------------------------记录日志中---------------");
      try {
       String[] reqInfo = UrlParser.parseReqGoal(request);
      
          Object visitClass = EasywebContext.Factory.getInstance().getBeanWithBlhAnnotation(reqInfo[0]);
      
          if (visitClass == null) { throw new BaseException(1002);
      }
          if (this.logger.isDebugEnabled()) {
            this.logger.debug("|>> Start " + Thread.currentThread().getId() + " " + reqInfo[0] + "_" + reqInfo[1]);
      }
      

          Method visitMethod = visitClass.getClass().getMethod(reqInfo[1], new Class[] { IZrarRequest.class });
      
          IZrarResponse rs = (IZrarResponse)visitMethod.invoke(visitClass, new Object[] { zrarRequest });
      
          String error = rs.getError();
          if (StringUtil.isNotNull(error)) {
            throw new BusinessException(rs.getErrorCode(), error);
      }
            end = System.currentTimeMillis();
            endTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
            usedTime =String.valueOf((end-start)/1000).toString();
          System.out.println("------aop执行时间-----------"+(end-start));
          commite = "执行成功";
          System.out.println("----------------------------------记录日志结束---------------");
          dao.execute("insert into aoploginfo set id='"+id+"', startTime='"+startTime+"',endTime='"+endTime+"',usedTime='"+usedTime+"', visitUrl='"+visitUrl+"',userId='"+userId+"',userName='"+userName+"',commite='"+commite+"'");
          return rs;
    } catch (SecurityException e) {
    	commite = "执行异常";
          throw new BaseException("SecurityException", e);
    } catch (IllegalArgumentException e) {
    	commite = "执行异常";
          throw new BaseException("IllegalArgumentException", e);
    } catch (NoSuchMethodException e) {
    	commite = "执行异常";
          throw new BaseException(1002);
    } catch (IllegalAccessException e) {
    	commite = "执行异常";
          throw new BaseException(1003, e);
    } catch (InvocationTargetException e) {
    	commite = "执行异常";
           Throwable targetException = e.getTargetException();
          if (BaseException.class.isAssignableFrom(targetException.getClass())) {
            throw ((BaseException)targetException);
      }
      
          throw new BaseException(targetException);
    } catch (BaseException e) {
    	commite = "执行异常";
          throw e;
    } finally{
    	if("执行异常".equals(commite)){
    		 end = System.currentTimeMillis();
    		 endTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
             usedTime =String.valueOf((end-start)/1000).toString();
    		dao.execute("insert into aoploginfo set id='"+id+"', startTime='"+startTime+"',endTime='"+endTime+"',usedTime='"+usedTime+"', visitUrl='"+visitUrl+"',userId='"+userId+"',userName='"+userName+"',commite='"+commite+"'");
    	}
    }
       
  }
   

@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
		context = applicationContext; 
	
}
public static Object getBean(String name){ 
    return context.getBean(name); 
} 
}

  

 

posted @ 2018-06-12 11:00  魔流剑少  阅读(5618)  评论(0编辑  收藏  举报