工厂Bean
IOC操作Bean管理 (FactoryBean)
Spring有两种类型的bean,一种是普通的bean,另一种是工厂bean(FactoryBean)
普通bean
在配置文件中定义bean类型就是返回类型
工厂bean
在配置文件定义bean类型可以和返回类型不一样
创建类,让这个类作为工厂bean,实现接口FactoryBean
实现接口里面的方法,在实现的方法中定义返回的bean类型
package com.test2;
public class Course {
private String cname;
public void setCname(String cname) {
this.cname = cname;
}
}
package com.test2;
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("adc");
return course;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
<?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.test2.MyBean"/>
</beans>
package com.test2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyBeanTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring6.xml");
MyBean myBean = context.getBean("myBean", MyBean.class);
System.out.println("myBean = " + myBean);
}
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring6.xml");
Course course = context.getBean("myBean", Course.class);
System.out.println("course = " + course);
}
}
