Spring_IOC容器:工厂Bean(Bean管理)
1.Spring 有两种类型的bean,,一种普通bean,另一种工厂bean(FactoryBean)
2.普通bean:在配置文件中定义bean类型就是返回类型
3.工厂bean:在配置文件定义bean类型可以和返回类型不一样
第一步:创建类。让这个类作为工厂bean,实现接口FactoryBean
第二步:实现接口里面的方法,在实现的方法中定义返回的bean类型
package com.tinstu.spring.factoryBean;
import com.tinstu.spring.collectiontype.Course;
import org.springframework.beans.factory.FactoryBean;
public class MyBean implements FactoryBean<Course> {
//定义返回的bean类型
@Override
public Course getObject() throws Exception {
Course course = new Course();
course.setCname("sss");
return course;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
<bean id="myBean" class="com.tinstu.spring.factoryBean.MyBean"></bean>
public class test {
@Test
public void testAdd(){
//加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
//获取配置创建对象
Course course = context.getBean("myBean",Course.class);
System.out.println(course);
}
}
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/1011.html
文章版权归作者所有,未经允许请勿转载。
THE END