用实例工厂的方法实例化bean
2024-09-28 07:52:54
在实例化bean时,除了setter,constructor方法外,还有实例工厂方法,和静态工厂方法。
看代码:
People类的代码如下:
package com.timo.domain; public class People {
private String name;
private Integer age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}
//工厂方法如下:
package com.timo.domain; public class PeopleFactory {
private static People people=new People();
//this is non-static method.
public People createPeopleInstance(){
return people;
}
}
配置文件
applicationContext-instance-factory.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">
<import resource="applicationContext.xml"/>
<import resource="applicationContext2.xml"/>
<bean id="peopleFactory" class="com.timo.domain.PeopleFactory"></bean>
<bean id="people" factory-bean="peopleFactory" factory-method="createPeopleInstance">
<property name="name" value="曹操"/>
<property name="age" value=""/>
</bean> <!-- more bean definitions go here --> </beans>
测试类如下:
package com.timo.test; import com.timo.domain.People;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test5 {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-instance-factory.xml");
People people = applicationContext.getBean(People.class);
System.out.println("name="+people.getName()+" age="+people.getAge());
}
}
最新文章
- BZOJ 3159决战
- MariaDB之基于Percona Xtrabackup备份大数据库[完整备份与增量备份]
- IOS UIScrollView中 使用 touch 无法响应的问题
- 转载:C# 之泛型详解
- 关于SVN版本控制器的问题与解决方法
- NSDictionary初始化,使用@{}方法,插入nil时会报空指针异常
- js 正则之检测素数
- Xshell利用登录脚本从服务器登录到另外一个服务器
- DOUAudioStreamer 中的DOUAudioFileProvider理解笔记
- SSH框架的多表查询(方法二)增删查改
- Javaweb-request与response
- hdu-4763(kmp+拓展kmp)
- hdfs 操作 入门api
- python if elif else判断语句
- CSS实现鼠标经过网页图标弹出微信二维码
- NXP ARM Vector Table CheckSum
- 2018.09.15 vijos1053Easy sssp(最短路)
- iOS开发证书与配置文件的使用
- SpringBoot 线程池配置 实现AsyncConfigurer接口方法
- C#.NET常见问题(FAQ)-如何批量增加或取消注释