1,基于构造方法注入
无参构造方法注入
无参构造方法注入就是Spring会自动调用类的无参构造方法来创建一个对象,然后再把这个对象提交到Spring容器。像前一篇里写的Person就不需要提交任何的参数。
有参构造方法注入
但是有一些对象是有一些属性的,这些属性的初始化是通过构造方法传递进去的。这个时候创建对象时就必须要指定对应的参数。
Spring提供了通过构造器传入参数注入对象的方法。
1.改造一下Person:
package com.xl.spring.xlIoc.beans;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class Person {
private Integer id;
private String name;
public void sayHello(String name){
System.out.println(this.name + " say hello to " + name);
}
}
2.修改注入配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 存放bean的容器 -->
<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:用来指定一个需要spring创建并注入到IOC容器的对象
id:表示这个对象的名字
class:表示类型,类的全限定名
constructor-arg:表示对应的构造方法的参数
name:表示参数的名字
value:表示参数的值
index:表示参数的位置,从0开始
-->
<bean id="person" class="com.xl.spring.xlIoc.beans.Person">
<constructor-arg index="0" value="1"/>
<constructor-arg name="name" value="金钟国"/>
</bean>
</beans>
测试:
package com.xl.spring.xlIoc.test;
import com.xl.spring.xlIoc.beans.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Ioc001 {
public static void main(String[] args) {
//1.通过配置文件获取到spring的上下文:获取Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("springioc.xml");
//2.获取对应想要用的对象,这一步是通知spring的ioc容器让它拿一个对象来
Person person = (Person) ac.getBean("person"); //通过id来获取对象
//3.可以调用对象的方法了
person.sayHello("宋智孝");
}
}
有参构造方法的注入缺陷
有参构造方法有一个小缺陷,假如Person类中有三个参数,然后定义了两个有参构造方法,两个方法都是只传两个参数。这个时候就会发现,始终有一个方法没有被调用到。因为Spring调用有参构造方法的逻辑是按照构造方法的定义顺序来的,从上往下找到第一个满足参数个数匹配的方法来调用。
想要解决这个问题很简单。
这么写就好了:
<bean id="person" class="com.xl.spring.xlIoc.beans.Person">
<constructor-arg name="nickName" value="懵懵"/>
<constructor-arg name="name" value="宋智孝"/>
</bean>
2,基于Setter注入
setter注入的原理是先调用无参构造方法来创建对象,然后掉用对应的set方法来为属性赋值。用setter注入的方式也可以解决之前那个有参构造方法的缺陷,并且可以提高可读性。
1.还是先改造Person:
package com.xl.spring.xlIoc.beans;
import lombok.Setter;
@Setter
public class Person {
private Integer id;
private String name;
private String nickName;
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}
2.通过property标签来注入对应的属性:
<!-- name:属性名
value:属性值 -->
<bean id="person" class="com.xl.spring.xlIoc.beans.Person">
<property name="id" value="1"/>
<property name="name" value="宋智孝"/>
<property name="nickName" value="懵懵"/>
</bean>
测试还是一样。