目录
在Spring 中,有两个很容易混淆的类:BeanFactory 和FactoryBean,它们都可以用来创建对象,设计都使用了于工厂模式。
是一个工厂,它的作用是管理Bean,BeanFactory定义了IOC容器的最基本形式,使用BeanFactory必须严格遵守其提供的最基本的接口
是一个能生产或者修饰对象生成的工厂Bean,但实例Bean的过程没有BeanFactory复杂。从Spring3.0开始,FactoryBean开始支持泛型,即接口声明改为FactoryBean
有三个方法:
创建User对象
- public class User {
-
- private String name;
-
- private String address;
-
- public User(String name, String address) {
- this.name = name;
- this.address = address;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getAddress() {
- return address;
- }
-
- public void setAddress(String address) {
- this.address = address;
- }
-
- @Override
- public String toString() {
- return "User{" +
- "name='" + name + '\'' +
- ", address='" + address + '\'' +
- '}';
- }
- }
创建UserFactoryBean
- public class UserFactoryBean implements FactoryBean
{ -
- @Override
- public User getObject() throws Exception {
- return new User("咩哥", "深圳");
- }
-
- @Override
- public Class> getObjectType() {
- return User.class;
- }
- }
创建配置文件factoryBean.xml
- "1.0" encoding="UTF-8"?>
"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">
-
-
"userFactoryBean" class="org.springframework.factorybean.UserFactoryBean"> -
测试代码
- public class Test {
-
- public static void main(String[] args) {
- ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("factoryBean.xml");
- User user = (User) ac.getBean("userFactoryBean");
- System.out.println(user);
- }
-
- }
上述代码获取的是User对象,即通过FactoryBean创建的对象,如果我们要获取FactoryBean本身,则可以使用转义字符”&”
- public static void main(String[] args) {
- ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("factoryBean.xml");
- UserFactoryBean userFactoryBean = (UserFactoryBean) ac.getBean("&userFactoryBean");
- System.out.println(userFactoryBean);
- }
上述代码创建的对象是单例,创建的User对象会放到缓存池中,如果不用单例,则不会放到缓存池中,并且每次创建的对象都是新对象
使用单例
不使用单例
重写FactoryBean中的default boolean isSingleton()方法,并将返回值设为false。
- public class UserFactoryBean implements FactoryBean
{ -
- @Override
- public User getObject() throws Exception {
- return new User("咩哥", "深圳");
- }
-
- @Override
- public Class> getObjectType() {
- return User.class;
- }
-
- @Override
- public boolean isSingleton() {
- return false;
- }
- }