【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 ...
随机推荐
- servlet种下cookie后如何携带cookie继续往下走
事情是这样的,今天我在应用1里面手动种下了一个cookie,然后它会发接着访问应用2,因为是我手动setCookie,所以它还没来得及携带cookie继续前往下一站,于是,apple pen,炸了. ...
- [Javascript] Check both prop exists and value is valid
Sometime you need to check one prop exists on the object and value should not be ´null´ or ´undefine ...
- 关于Promise的一些个人理解jQuery的deferred
一.什么是deferred对象? 开发网站的过程中,我们经常遇到某些耗时很长的javascript操作.其中,既有异步的操作(比如ajax读取服务器数据),也有同步的操作(比如遍历一个大型数组), ...
- JAVA 报错exe4j中this executable was created with an evaluation 怎么办
如果使用未破解注册的exe4j打包JAR文件为EXE,运行EXE的时候就会出现下面的提示 打开exe4j软件,Change License或者是输入序列号,然后用注册机算一个注册码即可
- Asp.Net 之 禁用TextBox的记忆功能
IE提供了一个自动完成功能可以记忆我们的输入内容(如登录帐号等),方便下一次快速地录入类似资料.这确实是一个非常友好的功能,在操作时只需用鼠标双击文本框或输入前几个字符,系统会自动列出以前的录入历史供 ...
- VMware的存储野心(上):软件定义、分布式DAS支持
ChinaByte比特网 http://storage.chinabyte.com/291/12477791_2.shtml 11月29日(文/黄亮)- SDN(软件定义的网络,Software De ...
- 在centos7中离线方式安装mysql5.7
第一步:下载mysql 在Linux终端使用wget命令下载网络资源:(可以先下好) wget http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-5.7.17 ...
- 树莓派3中运行Netcore2.0程序
一.简介 Netcore2.0发部后,可以运行在Arm平台上.因此,我们可以尝试在装了Debain的树莓派中运行. 二.方法: 1.在自己的电脑上使用VS写一个NetCore2.0的控制台程序,我假设 ...
- JAVA i++于++i的区别
大家看一下下面一个程序: 一.问题说明 Test.java public class Test { public static void main(String[] args) { int i = 1 ...
- js 树结构数据遍历条件判断
代码: /** * 树结构数据条件过滤 * js 指定删除数组(树结构数据) */ function filter (data, id) { var newData = data.filter(x = ...