欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring在代码中获取bean的方法小结

程序员文章站 2024-03-12 16:20:56
一、通过spring提供的contextloader webapplicationcontext wac = contextloader.getcurrentwe...

一、通过spring提供的contextloader

webapplicationcontext wac = contextloader.getcurrentwebapplicationcontext();
wac.getbean(beanid);

这种方式不依赖于servlet,不需要注入的方式。但是需要注意一点,在服务器启动时,spring容器初始化时,不能通过这种方法获取spring容器

二、实现接口applicationcontextaware

定义工具类

public class springcontextutil implements applicationcontextaware {
  private static applicationcontext applicationcontext;   //spring应用上下文环境

  /**
   * 实现applicationcontextaware接口的回调方法,设置上下文环境
   * @param applicationcontext
   * @throws beansexception
   */
  public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
    springcontextutil.applicationcontext = applicationcontext;
  }

  /**
   * @return applicationcontext
   */
  public static applicationcontext getapplicationcontext() {
    return applicationcontext;
  }

  /**
   * 获取对象
   * @param name
   * @return object 一个以所给名字注册的bean的实例
   * @throws beansexception
   */
  public static object getbean(string name) throws beansexception {
    return applicationcontext.getbean(name);
  }

  /**
   * 获取类型为requiredtype的对象
   * 如果bean不能被类型转换,相应的异常将会被抛出(beannotofrequiredtypeexception)
   * @param name    bean注册名
   * @param requiredtype 返回对象类型
   * @return object 返回requiredtype类型对象
   * @throws beansexception
   */
  public static object getbean(string name, class requiredtype) throws beansexception {
    return applicationcontext.getbean(name, requiredtype);
  }

  /**
   * 如果beanfactory包含一个与所给名称匹配的bean定义,则返回true
   * @param name
   * @return boolean
   */
  public static boolean containsbean(string name) {
    return applicationcontext.containsbean(name);
  }

  /**
   * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
   * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(nosuchbeandefinitionexception)
   * @param name
   * @return boolean
   * @throws nosuchbeandefinitionexception
   */
  public static boolean issingleton(string name) throws nosuchbeandefinitionexception {
    return applicationcontext.issingleton(name);
  }

  /**
   * @param name
   * @return class 注册对象的类型
   * @throws nosuchbeandefinitionexception
   */
  public static class gettype(string name) throws nosuchbeandefinitionexception {
    return applicationcontext.gettype(name);
  }

  /**
   * 如果给定的bean名字在bean定义中有别名,则返回这些别名
   * @param name
   * @return
   * @throws nosuchbeandefinitionexception
   */
  public static string[] getaliases(string name) throws nosuchbeandefinitionexception {
    return applicationcontext.getaliases(name);
  }
}

三、配置bean

<!-- springcontextutil 通过代码获取bean -->
<bean id="springcontextutil " class="org.shaofan.demo.utils.springcontextutil"/>

总结

以上就是spring在代码中获取bean的几种方式,希望本文的内容对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。