【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 ...
随机推荐
- CodeForces 569B Inventory 货物编号
原题: http://codeforces.com/contest/569/problem/B 题目: Inventory time limit per test1 second memory lim ...
- 教育单元测试mock框架优化之路(上)
转载:https://sq.163yun.com/blog/article/169561874192850944 众所周知,mock对于单元测试,尤其是基于spring容器的单元测试,是非常重要的.它 ...
- iOS 里RGB 配色 UIColor colorWithRed
//比如rgb 色值为73. 148 .230 那么ios 里面要在后面加.0f 再除以255 [bline setBackgroundColor:[UIColor colorWithRed:73.0 ...
- 016-Go Iris Restful测试
1:data/data.go package data import( "fmt" "database/sql" _"github.com/lib/p ...
- bat脚本禁用和开启本地连接
netsh interface set interface name="本地连接" admin=disabled //禁用本地连接 netsh interface set inte ...
- SpringBoot2中配置文件的调整,升级SpringBoot2时候注意的坑
原来使用SpringBoot1.5最近写个demo后发现原来的配置文件不能用了. 最后上网查询了一下资料,springboot2.0和spring1.x还是存在不少问题的. 1.问题一:Java版本要 ...
- 一个简单的 JSON 生成/解析库
这是一个单文件的,适用于C语言的, JSON 读写库. 先说明,不想造轮子,代码是从这里拿来的: https://www.codeproject.com/Articles/887604/jWrite- ...
- vue $options 获取自定义属性
说明: https://cn.vuejs.org/v2/api/#vm-options 用于当前 Vue 实例的初始化选项.需要在选项中包含自定义属性时会有用处. element-ui代码中经常定义组 ...
- V-rep学习笔记:机器人逆运动学解算
IK groups and IK elements VREP中使用IK groups和IK elements来进行正/逆运动学计算,一个IK group可以包含一个或者多个IK elements: I ...
- 三种常用的MySQL建表语句
MySQL建表语句是最基础的SQL语句之一,下面就为您介绍最常用的三种MySQL建表语句,如果您对MySQL建表语句方面感兴趣的话,不妨一看. 1.最简单的: CREATE TABLE t1( ...