获取Spring Bean 的几种方法.

来源:互联网 发布:在线网络直播电视 编辑:程序博客网 时间:2024/05/12 07:27

1 .WebApplicationContextUtils    .getRequiredWebApplicationContext(servlet.getServletContext());   
public Object getBean(String name)   
  {   
      if (ctx == null)   
      {   
          ctx = WebApplicationContextUtils   
                .getRequiredWebApplicationContext(servlet.getServletContext());   
      }   
      return ctx.getBean(name);   
  }

2. public static void main(final String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", Boot.class); //必需放在WEB-INF/lib/class下面
        FooService fooService = (FooService) ctx.getBean("fooService");
        fooService.insertFoo (new Foo());
    }


3. ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "src/cn/com/jbaptech/po/applicationContext.xml" });ctx.getBean("fooService");


原创粉丝点击