FactoryBean是一个接口,需要创建一个类实现该接口其中有三个方法:
getobject():通过一个对象交给IOC容器管理getobjectType( ):设置所提供对象的类型issingleton( ):所提供的对象是否单例
当把FactoryBean的实现类配置为bean时,会将当前类中getobject()所返回的对象交给IOC容器管理
创建UserfactoryBean继承FactoryBean:
package com.Factory;
import com.Student;
import org.springframework.beans.factory.FactoryBean;
public class UserfactoryBean implements FactoryBean<Student> {
@Override
public Student getObject() throws Exception {
return new Student();
}
@Override
public Class<?> getObjectType() {
return Student.class;
}
}
.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">
<!-- 虽然写的是UserfactoryBean,但其实getObject返回了一个Student对象,之后调用ioc直接调用Student.class即可-->
<bean class="com.Factory.UserfactoryBean"></bean>
</beans>
package test;
import com.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class factoryTest {
@Test
public void test(){
ApplicationContext ioc = new ClassPathXmlApplicationContext();
Student bean = ioc.getBean(Student.class);
}
}