首页 > 代码库 > BeanFactory和FactoryBean

BeanFactory和FactoryBean

BeanFactory

BeanFactory是Spring的IOC容器的接口,用于获取Java对象。

ApplicationContext接口也间接扩展了BeanFactory接口,是BeanFactory接口的子接口,继承树如下所示:

BeanFactory

↑                     ↑

ListableBeanFactory    HierarchicalBeanFactory

↑                     ↑

ApplicationContext

BeanFactory的代码如下:

package org.springframework.beans.factory;

import org.springframework.beans.BeansException;

public interface BeanFactory {

String FACTORY_BEAN_PREFIX = "&";

Object getBean(String name) throws BeansException;

<T> T getBean(String name, Class<T> requiredType) throws BeansException;

<T> T getBean(Class<T> requiredType) throws BeansException;

Object getBean(String name, Object... args) throws BeansException;

boolean containsBean(String name);

boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException;

Class<?> getType(String name) throws NoSuchBeanDefinitionException;

String[] getAliases(String name);

}

FactoryBean

FactoryBean也是接口,用于辅助Spring生成构造过程比较复杂的Java对象。

FactoryBean接口的代码如下所示:

package org.springframework.beans.factory;

public abstract interface FactoryBean<T> {

public abstract T getObject() throws Exception;

public abstract Class<?> getObjectType();

public abstract boolean isSingleton();

}

例如,有需求如下所述,用Spring配置生成Job类的实例,Job类有个属性叫做workday,生成Job类实例的时候需要给该属性赋值为“当前日期的上一个工作日”。显然,想要计算出“当前日期的上一个工作日”不是个简单的事情,用Spring配置很难实现。这时候FactoryBean就派上用场了。

假设Job类的代码如下:

package test.bean;

import java.util.Date;

public class Job {

private Date workday;

public Job() {}

public Date getWorkday() {

return workday;

}

public void setWorkday(Date workday) {

this.workday = workday;

}

}

用于构建Job类实例的FactoryBean如下:

package test.bean;

import java.util.Date;

import org.springframework.beans.factory.FactoryBean;

public class JobFactoryBean implements FactoryBean<Job> {

public Job getObject() throws Exception {

Job job = new Job();

Date workday = null;

// TODO 计算出当前日期的上一个工作日,计算过程省略。。。

job.setWorkday(workday);

return job;

}

public Class<?> getObjectType() {

return Job.class;

}

public boolean isSingleton() {

return false;

}

}

需要在applicationContext.xml中把这个JobFactoryBean配置进去:

<bean id="job" class="test.bean.JobFactoryBean"></bean>

最后,写代码做个测试:

public static void main(String[] args) {

ApplicationContext ctx =

new ClassPathXmlApplicationContext("/applicationContext.xml");

Job job = (Job) ctx.getBean("job");

System.out.println(job.getWorkday());

}

注意,上面的代码获得的bean是由JobFactoryBean对象创建出来的Job对象,如果要想通过Spring来获得JobFactoryBean的对象,需要修改一下代码:

把ctx.getBean("job")改成ctx.getBean("&job")。

这样返回的对象就是JobFactoryBean这个类的对象了。