跳转至

Spring 继承FactoryBean来创建对象

1. 介绍

  FactoryBean是Spring规定的一个接口,当前接口的实现类,Spring都会将其作为一个工厂,但是在ioc容器启动的时候不会创建实例,只有在使用的时候才会创建对象。

2. 示例

ioc6.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 id="myFactoryBean" class="com.cmz.factory.MyFactoryBean"></bean>
</beans>

MyFactoryBean.class

package com.cmz.factory;

import com.cmz.bean.Person;
import org.springframework.beans.factory.FactoryBean;

/**
 * @author summer
 * @create 2020-02-29 14:55
 */
public class MyFactoryBean implements FactoryBean<Person> {

    /**
     * 工厂方法,返回需要创建的对象
     * @return
     * @throws Exception
     */
    public Person getObject() throws Exception {
        Person person = new Person();
        person.setName("蔡猛芝");
        person.setId(6);
        return person;
    }

    /**
     * 返回创建对象的类型,spring会自动调用该方法返回对象的类型
     * @return
     */
    public Class<?> getObjectType() {
        return Person.class;
    }

    /**
     * 创建的对象是否是单例对象
     * @return
     */
    public boolean isSingleton() {
        return false;
    }
}

MyTest6.class

import com.cmz.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author summer
 * @create 2020-02-22 23:45
 */
public class MyTest6 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc6.xml");
        Person person = context.getBean("myFactoryBean", Person.class);
        System.out.println(person);
    }
}

输出

Person{id=6, name='蔡猛芝', age=null, gender='null', date=null}