IOC操作Bean管理(普通Bean和FactoryBean)
1、Spring有两种类型Bean,一种是普通Bean,另一种工厂Bean(FactoryBean)
2、普通Bean:在配置文件中定义bean类型就是返回的类型
3、工厂Bean:在配置文件中定义bean类型可以和返回类型不一样(Spring中内置bean的类型)
第一步:创建类,让这个类作为工厂Bean,实现接口FactoryBean
第二部:实现接口里面的方法,在实现的方法中定义返回的Bean类型
- 工厂Bean
/**
* @Description: MyBean实现FactoryBean
* @Author: lds
* @Date: 2020/12/12
*/
public class MyBean implements FactoryBean<Course> {
/**
* 定义返回的bean
*/
public Course getObject() throws Exception {
Course course = new Course();
course.setName("abc");
return course;
}
public Class<?> getObjectType() {
return null;
}
}
- xml配置
<bean id="myBean" class="com.lds.springdemo.factorybean.MyBean"> </bean>
- 测试类配置
/**
* @author LDS
* 测试类
*/
public class DemoTest {
@Test
public void test() {
//1、加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext5.xml");
//2、获取配置创建的对象
Course course = context.getBean("myBean", Course.class);
System.out.println(course);
}
}