一、概述
- Spring中有2种类型的Bean,一种是普通Bean,另外一种是工厂Bean(FactoryBean);
- 普通Bean:在配置文件中定义的Bean的类型就是返回类型;
- 工厂Bean:在配置文件中定义的Bean的类型可以和返回类型不一样;
(1)创建类,让这个类作为工厂bean,实现接口FactoryBean;
(2)实现接口里边的方法,在实现的方法中定义返回的Bean的类型;
二、自定义Bean创建对象
// 工厂类
public class MyFactoryBean implements FactoryBean<Course> {@Overridepublic Course getObject() throws Exception {Course course = new Course("Springboot课程");return course;}@Overridepublic Class<?> getObjectType() {return null;}@Overridepublic boolean isSingleton() {return false;}
}// 配置文件
<?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="org.star.factory.MyFactoryBean"></bean></beans>// 测试
/*** Bean管理:使用自定义Bean创建对象*/
@Test
public void beanManagementTest8() {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext9.xml");Course course = context.getBean("myFactoryBean", Course.class);System.out.println(course);
}
// 结果
Course(name=Springboot课程)