Spring入门(2)-通过构造器注入Bean
Spring入门(2)-通过构造器注入Bean
前一篇文章将了最基本的spring例子,这篇文章中,介绍一下带有参数的构造函数和通过构造器注入对象引用。
0. 目录
- 带有参数的构造函数
- 通过构造器注入对象引用
- 通过工厂方法创建Bean
1. 带有参数的构造函数
把需要实例化的类中增加一个有参数的构造函数
package com.chzhao.springtest;
public class PersonBll implements IPersonBll {
private Person person;
public PersonBll() {
}
public PersonBll(String name) {
this.person = new Person();
this.person.setName(name);
}
public void show() {
if (this.person != null) {
System.out.println(this.person.getName());
} else {
System.out.println("no person");
}
}
public void addPerson(Person p) {
System.out.println("add person: " + p.getName());
}
}
配置文件
<?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 name="PersonBll" class="com.chzhao.springtest.PersonBll">
<constructor-arg value="老王"></constructor-arg>
</bean>
</beans>
通过这种方式,可以把参数传入到构造函数中。
2. 通过构造器注入对象引用
把构造函数改为引用类型,代码如下:
package com.chzhao.springtest;
public class PersonBll implements IPersonBll {
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public PersonBll() {
}
public PersonBll(Person p) {
this.person = p;
}
public void show() {
if (this.person != null) {
System.out.println(this.person.getName());
} else {
System.out.println("no person");
}
}
public void addPerson(Person p) {
System.out.println("add person: " + p.getName());
}
}
同时配置文件改为
<?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 name="laowang" class="com.chzhao.springtest.Person">
<property name="name" value="老王" />
</bean>
<bean name="PersonBll" class="com.chzhao.springtest.PersonBll">
<constructor-arg ref="laowang"></constructor-arg>
</bean>
</beans>
3. 通过工厂方法创建Bean
有时候一些对象是通过工厂方法实例化的,这里介绍一下。
package com.chzhao.springtest;
public class BllFactory {
public static PersonBll getPersonBll() {
Person p = new Person();
p.setName("老李");
PersonBll bll = new PersonBll(p);
return bll;
}
}
对应配置文件
<?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 name="PersonBll" class="com.chzhao.springtest.BllFactory"
factory-method="getPersonBll">
</bean>
</beans>