转自:http://www.sohu.com/a/115194552_466964

我们知道可以通过ApplicationContext的getBean方法来获取Spring容器中已初始化的bean。getBean一共有以下四种方法原型:

l getBean(String name)

l getBean(Class<T> type)

l getBean(String name,Class<T> type)

l getBean(String name,Object[] args)

下来我们分别来探讨以上四种方式获取bean的区别。

首先本案例项目包结构如下图:

其中实体类Person定义如下:

public class Person {

private String name;

private int age;

public Person()

{

}

public Person(String name, int age) {

this.name = name;

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Override

public String toString() {

return "Person [name=" + name + ", age=" + age + "]";

}

}

applicationContext.xml注册有id为p的bean,配置如下:

<bean id="p" class="com.bean.Person">

<property name="name" value="张三"/>

<property name="age" value="18"/>

</bean>

l getBean(String name)

参数name表示IOC容器中已经实例化的bean的id或者name,且无论是id还是name都要求在IOC容器中是唯一的不能重名。那么这种方法就是通过id或name去查找获取bean.获取bean的参考代码如下:

@Test

public void testPerson()

{

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Person p = (Person) ctx.getBean("p");

System.out.println(p);

}

l getBean(Class<T> type)

参数Class<T> type表示要加载的Bean的类型。如果该类型没有继承任何父类(Object类除外)和实现接口的话,那么要求该类型的bean在IOC容器中也必须是唯一的。比如applicationContext.xml配置两个类型完全一致的bean,且都没有配置id和name属性。

<bean class="com.bean.Person">

<property name="name" value="张三"/>

<property name="age" value="18"/>

</bean>

<bean class="com.bean.Person">

<property name="name" value="李四"/>

<property name="age" value="20"/>

</bean>

那么通过com.bean.Person这种类型来查找bean,参考代码如下:

@Test

public void testPerson()

{

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Person p = ctx.getBean(Person.class);

System.out.println(p);

}

但是由于属于com.bean.Person的bean在IOC容器中不唯一,所以这里会抛出NoUniqueBeanDefinitionException异常。

由此我们可以总结getBean(String name)和getBean(Class<T> type)的异同点。

相同点:都要求id或者name或者类型在容器中的唯一性。

不同点:getBean(String name)获得的对象需要类型转换而getBean(Class<T> type)获得的对象无需类型转换。

l getBean(String name,Class<T> type)

这种方式比较适合当类型不唯一时,再通过id或者name来获取bean。

例如applicationContext.xml配置有如下bean:

<bean id="p1" class="com.bean.Person">

<property name="name" value="张三"/>

<property name="age" value="18"/>

</bean>

<bean name="p2" class="com.bean.Person">

<property name="name" value="李四"/>

<property name="age" value="20"/>

</bean>

参考代码如下:

@Test

public void testPerson()

{

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Person p = ctx.getBean("p2",Person.class);

System.out.println(p);

}

这样可以获取到名字叫”李四”的对象。测试结果如下:

l getBean(String name,Object[] args)

这种方式本质还是通过bean的id或者name来获取bean,通过第二个参数Object[] args可以给bean的属性赋值,赋值的方式有两种:构造方法和工厂方法。但是通过这种方式获取的bean必须把scope属性设置为prototype,也就是非单例模式。

先在com.factory包下设计有如下的工厂类:

public class PersonFactory {

//静态工厂注入

public static Person getPersonInstance(String name,int age)throws Exception

{

Person p = (Person)Class.forName("com.bean.Person").newInstance();

Method m = p.getClass().getMethod("setName", java.lang.String.class);

m.invoke(p, name);

m = p.getClass().getMethod("setAge", int.class);

m.invoke(p, age);

return p;

}

}

在applicationContext.xml中配置有如下bean:

<bean name="p3" class="com.bean.Person" scope="prototype"/>

获取bean的参考代码如下:

@Test

public void testPerson()

{

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Person p = (Person) ctx.getBean("p3",new Object[]{"王五",35});

System.out.println(p);

}

如果想通过工厂注入属性,在applicationContext.xml配置如下bean:

<bean name="p3" class="com.factory.PersonFactory" factory-method="getPersonInstance" scope="prototype">

<constructor-arg name="name">

<null/>

</constructor-arg>

<constructor-arg name="age" value="0"/>

</bean>

ApplicationContext之getBean方法详解的更多相关文章

  1. Spring IoC getBean 方法详解

    前言 本篇文章主要介绍 Spring IoC 容器 getBean() 方法. 下图是一个大致的流程图: 正文 首先定义一个简单的 POJO,如下: public class User { priva ...

  2. spring获取webapplicationcontext,applicationcontext几种方法详解

    法一:在初始化时保存ApplicationContext对象代码: ApplicationContext ac = new FileSystemXmlApplicationContext(" ...

  3. 【spring框架】spring获取webapplicationcontext,applicationcontext几种方法详解--(转)

    方法一:在初始化时保存ApplicationContext对象代码:ApplicationContext ac = new FileSystemXmlApplicationContext(" ...

  4. spring获取webapplicationcontext,applicationcontext几种方法详解(转)

    方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemXmlApplicationContext(&quo ...

  5. spring获取webapplicationcontext,applicationcontext几种方法详解(转载)

    转载自  http://www.blogjava.net/Todd/archive/2010/04/22/295112.html 方法一:在初始化时保存ApplicationContext对象 代码: ...

  6. session的使用方法详解

    session的使用方法详解 Session是什么呢?简单来说就是服务器给客户端的一个编号.当一台WWW服务器运行时,可能有若干个用户浏览正在运正在这台服务器上的网站.当每个用户首次与这台WWW服务器 ...

  7. Kooboo CMS - Html.FrontHtml[Helper.cs] 各个方法详解

    下面罗列了方法详解,每一个方法一篇文章. Kooboo CMS - @Html.FrontHtml().HtmlTitle() 详解 Kooboo CMS - Html.FrontHtml.Posit ...

  8. HTTP请求方法详解

    HTTP请求方法详解 请求方法:指定了客户端想对指定的资源/服务器作何种操作 下面我们介绍HTTP/1.1中可用的请求方法: [GET:获取资源]     GET方法用来请求已被URI识别的资源.指定 ...

  9. ecshop后台增加|添加商店设置选项和使用方法详解

    有时候我们想在Ecshop后台做个设置.radio.checkbox 等等来控制页面的显示,看看Ecshop的设计,用到了shop_config这个商店设置功能 Ecshop后台增加|添加商店设置选项 ...

随机推荐

  1. learning rndis protocol

    reference:  https://docs.microsoft.com/en-us/windows-hardware/drivers/network/overview-of-remote-ndi ...

  2. Vue + Element UI 实现权限管理系统(第三方图标库)

    使用第三方图标库 用过Elment的同鞋都知道,Element UI提供的字体图符少之又少,实在是不够用啊,幸好现在有不少丰富的第三方图标库可用,引入也不会很麻烦. Font Awesome Font ...

  3. spoj705

    题解: 后缀数组求出height 然后ans=所有串-所有height 代码: #include<bits/stdc++.h> using namespace std; ; int t,a ...

  4. docker pure-ftpd

    FROM alpine:3.7ADD http://dl-4.alpinelinux.org/alpine/edge/testing/x86_64/pure-ftpd-1.0.47-r0.apk /r ...

  5. 某些material英文翻译

    chrome  铬,铬合金, 镀铬 matte  无光泽的,不光滑的 Decal   陶瓷的 duo color  双色 livery  (这个没找到什么吊意思,我看像是一个类似打logo的材质)

  6. C++基础知识:继承

    1.继承的概念 面向对象中的继承指类之间的父子关系子类拥有父类的所有成员变量和成员函数子类就是一种特殊的父类子类对象可以当作父类对象使用子类可以拥有父类没有的方法和属性 2.C++中的访问级别与继承p ...

  7. python的list和tuple

    list Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素. 比如,列出班里所有同学的名字,就可以用一个list表示: >>> ...

  8. Github拉取远端的时候提示“ssh: connect to host github.com port 22: Connection timed out”错误

    在使用Github的时候,如果使用到拉取远端分支的时候或者测试ssh -T git@github.com的时候可能会出现连接失败的问题,错误描述为“ssh: connect to host githu ...

  9. NioEventLoop中的thread什么时候启动

    在构造函数中被赋值,并传入传入runnable接口,方法里面循环select,然后处理找到的key 但是这个thread是什么时候被start的呢? 在bootstrap bind的逻辑里,后半部分是 ...

  10. unity3d 九宫密码锁

    using UnityEngine;using System.Collections.Generic;using System;using UnityEngine.EventSystems;using ...