- Spring有两种类型bean,一种是普通bean,另外一种工厂FactoryBean
- 普通bean:在配置文件中定义为bean类型就是返回类型。
- 工厂bean:在配置文件定义bean类型可以和返回类型不一样。
步骤:
- 第一步,先创建类作为工厂bean,实现接口FactoryBean。
- 第二步,实现接口里面的方法,在实现的方法中定义返回的bean类型。
xml文件
<bean id="beanF" class="com.zcc.spring.service.BeanImpl"/>
Java
package com.zcc.spring.service;
import com.zcc.spring.pojo.Course;
import org.springframework.beans.factory.FactoryBean;
/**
* @author 23839
*/
public class BeanImpl implements FactoryBean<Course> {
@Override
public Course getObject() throws Exception {
return new Course("zcc123");
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
运行
@Test
public void test6() {
ApplicationContext context = new ClassPathXmlApplicationContext("xmls/BeanFirty.xml");
Course course = context.getBean("beanF",Course.class);
System.out.println("course.toString() = " + course.toString());
}