IOC操作Bean管理(FactoryBean)
1.Spring有两种类型bean,一种普通bean,另外一种工厂bean(FactoryBean)
2.普通bean:在配置文件中定义bean类型就是返回类型
3.工厂bean:在配置文件定义bean类型可以和返回类型不一样
第一步 创建类,让这个类作为工厂bean,实现接口FactoryBean
第二步 实现接口里面的方法,在实现的方法中定义返回的bean类型
package com.atguigu.spring.collectiontype;public class Course {private String cname;public void setCname(String cname) {this.cname = cname;}
}
package com.atguigu.spring.factoryBean;import com.atguigu.spring.collectiontype.Course;
import org.springframework.beans.factory.FactoryBean;public class MyBean implements FactoryBean<Course> {//定义返回bean@Overridepublic Course getObject() throws Exception {Course course = new Course();course.setCname("abc");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 = "myBean" class = "com.atguigu.spring.factoryBean.MyBean"></bean></beans>
测试:
package com.atguigu.spring.test;import com.atguigu.spring.collectiontype.Book;
import com.atguigu.spring.collectiontype.Course;
import com.atguigu.spring.factoryBean.MyBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class testBook {@Testpublic void testCollection2(){ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");Course myBean = context.getBean("myBean", Course.class);System.out.println(myBean);}}