1.普通bean与工厂bean
Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)
- 普通 bean:在配置文件中定义 bean 类型就是返回类型
- 工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样
2.工厂bean的步骤
- 创建类,让这个类作为工厂 bean,实现接口 FactoryBean
public class MyFactoryBean implements FactoryBean<Student> {
//定义返回 bean
@Override
public Student getObject() throws Exception {
Student student = new Student();
student.setName("工厂bean");
return student;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
实现接口里面的方法,在实现的方法中定义返回的 bean 类型
//定义返回 bean
@Override
public Student getObject() throws Exception {
Student student = new Student();
student.setName("工厂bean");
return student;
}
代码示例:
Student类:
public class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
xml文件:
<?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="iocbean.byxml.factorybean.MyFactoryBean">
</bean>
</beans>
测试类:
public class TestDemo {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/factorybean/bean.xml");
Student bean = context.getBean("myFactoryBean", Student.class);
System.out.println(bean);
}
}
输出结果:
Student{name='工厂bean', age=0, gender='null'} Process finished with exit code 0