【Spring】Spring之向 IOC 容器注入对象的三种方式
关于Spring的搭建可参见:浅析Spring框架的搭建.在测试之前还是应该先将环境配置好,将相关Jar包导进来。Spring创建的对象,默认情况下都是单例模式,除非通过scope指定。
向IOC容器中注入对象,通过配置XML文件的<bean>节点来实现,<bean>中最主要的属性有两个,id和class,id表示标识这个<bean>节点,class表示关联的类文件名称(包名 + 类名)。<property>节点可以调用类中的setter方法,name对应参数名称,value对应传入的参数值。<constructor-arg>节点可以调用类中的构造器,name对应参数名称,value对应参数值。
一、通过构造函数创建对象。
2.1 利用无参构造函数+setter方法注入值
最基本的对象创建方式,只需要有一个无参构造函数(类中没有写任何的构造函数,默认就是有一个构造函数,如果写了任何一个构造函数,默认的无参构造函数就不会自动创建哦!!)和字段的setter方法。
Person类:

package com.mc.base.learn.spring.bean;
public class Person {
private String name;
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
}

XML配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="com.mc.base.learn.spring.bean.Person" id="person">
<property name="name" value="LiuChunfu"></property>
<property name="id" value="125"></property>
</bean> </beans>

其本质为:
SpringContext利用无参的构造函数创建一个对象,然后利用setter方法赋值。所以如果无参构造函数不存在,Spring上下文创建对象的时候便会报错。

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person' defined in class path resource [applicationContext.xml]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mc.base.learn.spring.bean.Person]: No default constructor found;
nested exception is java.lang.NoSuchMethodException: com.mc.base.learn.spring.bean.Person.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105)
。。。。。

2.2 利用有参构造函数直接注入
Person类:

package com.mc.base.learn.spring.bean;
public class Person {
private String name;
private Integer id;
public Person(String name, Integer id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
}

XML配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="com.mc.base.learn.spring.bean.Person" id="person">
<constructor-arg name="id" value="123"></constructor-arg>
<constructor-arg name="name" value="LiuChunfu"></constructor-arg>
</bean> </beans>

二、通过静态工厂方式创建对象。
静态工厂的对象,在容器加载的时候就被创建了。

package com.mc.base.learn.spring.factory;
import com.mc.base.learn.spring.bean.Person;
public class PersonStaticFactory {
public static Person createPerson(){
return new Person();
}
/**
* 工厂方法带有参数如何处理?
* @Title: createPerson
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param id
* @param @param name
* @param @return
* @return Person 返回类型
* @throws
*/
public static Person createPerson(Integer id,String name){
return new Person(name,id);
}
}

<!--静态的工厂方法核心是class+factory-method -->
<bean id="person" class="com.mc.base.learn.spring.factory.PersonStaticFactory" factory-method="createPerson">
<!--通过property方法向createPerson传递参数 -->
<property name="name" value="LiuChunfu"></property>
<property name="id" value="125"></property>
</bean>
测试如下:
@Test
public void testName() throws Exception {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Person person=ac.getBean("person3", Person.class);
System.out.println(person);//Person [name=LiuChunfu, id=125]
}
三、通过实例工厂方式创建对象。
实例工厂,就是通过实例来调用对象,但是所得到的对象最终也是单利模式。实例工厂和静态工厂创建的对象都是单例模式,两者的区别就是创建对象的实际不同,静态工厂是在创建容器的时候就创建了,实例工厂是在调用方法的时候才创建。知道Java设计模式中的单例模式设计(饿汉式和懒汉式)的读者,对这里的静态工厂模式和实例工厂模式肯定有所体会。

package com.mc.base.learn.spring.factory;
import com.mc.base.learn.spring.bean.Person;
public class PersonFactory {
public Person createInstance() {
return new Person();
}
}

<bean id="personFactory" class="cn.test.util.PresonFactoryInstance"></bean>
<bean id="person4" factory-bean="personFactory" factory-method="createPerson">
<property name="name" value="LiuChunfu"></property>
<property name="id" value="125"></property>
</bean>
@Test
public void testName() throws Exception {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Person person=ac.getBean("person4",Person.class);
System.out.println(person);//Person [name=LiuChunfu, id=125]
}
当然上面的创建对象传递参数,除了能够在创建对象的时候通过传入默认的参数,也可以在后面通过setter方法进行传参。
本Blog传递的参数只是简单的几种,关于向IOC容器中传入参数更详细请参见Sprinng之依赖注入传递参数的方式
原文连接:Spring创建对象的三种方式
【Spring】Spring之向 IOC 容器注入对象的三种方式的更多相关文章
- Spring为IOC容器注入Bean的五种方式
一 @Import导入组件,id默认是组件的全类名 //类中组件统一设置.满足当前条件,这个类中配置的所有bean注册才能生效: @Conditional({WindowsCondition.clas ...
- spring中创建bean对象的三种方式以及作用范围
时间:2020/02/02 一.在spring的xml配置文件中创建bean对象的三种方式: 1.使用默认构造函数创建.在spring的配置文件中使用bean标签,配以id和class属性之后,且没有 ...
- 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件 内容简介:本文介绍 Spring Boot 的配置文件和配置管理,以及介绍了三种读取配置文 ...
- Java反射机制(创建Class对象的三种方式)
1:了解什么是反射机制? 在通常情况下,如果有一个类,可以通过类创建对象:但是反射就是要求通过一个对象找到一个类的名称: 2:在反射操作中,握住一个核心概念: 一切操作都将使用Object完成,类 ...
- JDBC 创建连接对象的三种方式 、 properties文件的建立、编辑和信息获取
创建连接对象的三种方式 //第一种方式 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ ...
- Java反射机制(创建Class对象的三种方式)
1:SUN提供的反射机制的类: java.lang.Class<T> java.lang.reflect.Constructor<T> java.lang.reflect.Fi ...
- 反射:获取Class对象的三种方式
获取Class对象的三种方式 package lianxiApril18; /** * 获取Class对象的三种方式 * 1 Object ——> getClass(); * 2 任何数据类型( ...
- Java反射获取类对象的三种方式
package demo01; /* * 获取一个类的class文件对象的三种方式 * 1.对象获取 * 2.类名获取 * 3.Class类的静态方法获取 */ public class Reflec ...
- Java反射获取class对象的三种方式,反射创建对象的两种方式
Java反射获取class对象的三种方式,反射创建对象的两种方式 1.获取Class对象 在 Java API 中,提供了获取 Class 类对象的三种方法: 第一种,使用 Class.forName ...
随机推荐
- (转)NGUI中深度depth和z轴关系
先列出转载链接: http://game.ceeger.com/forum/read.php?tid=8917 转载原文: 问题源自一个帖子,因为上传的图比较多,就另开了这个贴写下自己的试验结果,原帖 ...
- 可以在任何时候attach一个shader到program对象
可以在任何时候attach一个shader到program对象,不一定非要在指定source和编译以后,具体的描述如下: Once you have a program object create ...
- 如何通过 iframe 共享 jQuery $.data?
index.html <div id="div1"> </div> <iframe src="ajax2.html" name=& ...
- JAVA基础编程50题(4-6题)具体解释
一.描写叙述 1.将一个正整数分解质因数.比如:输入90,打印出90=2*3*3*5. 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完毕: (1)假设这个质数恰等于n,则说明 ...
- 造轮子 | 怎样设计一个面向协议的 iOS 网络请求库
近期开源了一个面向协议设计的网络请求库 MBNetwork,基于 Alamofire 和 ObjectMapper 实现,目的是简化业务层的网络请求操作. 须要干些啥 对于大部分 App 而言,业务层 ...
- NSobject 结构
参考地址: https://iosdevelopmenttutorials.wordpress.com/tag/uiscrollview/ Apple Documentation
- Jquery——动画效果
jquery中常用的动画的方法就是hide()与show(). $(element).hide()这段代码可以与这相等element.css("display","non ...
- 微信小程序 - 3d轮播图组件(基础)
<!-- 目前仅支持data数据源来自banner,请看测试案例 ################ 以上三种形式轮播: 1. basic 2. 3d 3. book basic即普通轮播 3d即 ...
- vCenter Server Virtual Appliance features and benefits
http://vmwire.com/tag/vcsa/ Installed on SUSE Linux Enterprise Server 11 x64. OVF when deployed is c ...
- 树莓派系统(Debain)中设置固定静态IP地址
一.方法: 1.使用ssh登陆,使用以下命令设置静态ip. sudo nano /etc/dhcpcd.conf2.在dhcpcd.conf后添加以下内容(网上的方法): interface eth0 ...