转自: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. js作用域及闭包

    作用域 执行环境是js最为重要的一个概念.执行环境定义了变量或函数有权访问的其他数据,决定了它们各自的行为. 1.全局执行环境就是最外围的一个执行环境,每一个函数都有自己的作用域 2.简单的说局部作用 ...

  2. Python Django 之 直接执行自定义SQL语句(一)

    一.执行自定义SQL方法 1.Executing custom SQL directly      直接执行自定义SQL,这种方式可以完全避免数据模型,而是直接执行原始的SQL语句. 2.Manage ...

  3. Cracking The Coding Interview 9.7

    //原文: // // A circus is designing a tower routine consisting of people standing atop one another's s ...

  4. SQL-7查找薪水涨幅超过15次的员工号emp_no以及其对应的涨幅次数t (group 与count)

    题目描述 查找薪水涨幅超过15次的员工号emp_no以及其对应的涨幅次数tCREATE TABLE `salaries` (`emp_no` int(11) NOT NULL,`salary` int ...

  5. Java进程和线程

    进程是资源分配和任务调度的基本单位, 进程就是包含上下文切换的程序执行时间总和=CPU加载上下文环境+CPU执行+CPU保存上下文环境,可以理解为时间片段: 进程的颗粒度太大了,将进程分块,按照a,c ...

  6. easyui 日期控件限制起始相差30天

    $('#lendDateStart').datebox('calendar').calendar({ validator: function(date){ var endDateStr = $('#l ...

  7. 3-D models provided some resources

    http://d-earth.jamstec.go.jp/GAP_P4/ http://ds.iris.edu/ds/products/emc-earthmodels/

  8. 使用FileResult导出Excel数据文件

    用的是Html拼接成Table表格的方式,返回 FileResult 输出一个二进制的文件. 第一种:使用FileContentResult // 通过使用文件内容,内容类型,文件名称创建一个File ...

  9. ylz简单增删改查实现

    首先用generator实现三个文档 分别是实体类(domain文件夹下) xml配置和dao层文件. resource文件夹下 注意位置事先写死了,要根据要求文档来定义位置. package com ...

  10. 2019.3.5 L261 Are All Our Organs Vital?

    Medicine has not always shown a lot of respect for the human body. Just think about the ghoulish dis ...