一、工厂Bean

在配置文件中定义Bean类型可以和返回类型不一样

第一步,创建类,让这个类作为工厂Bean,实现接口FactoryBean

第二步,实现接口里面的方法,在实现的方法中定义返回的Bean类型

二、创建类

package com.leo.spring5.factorybean;

import com.leo.spring5.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("abc");
return course;
}

@Override
public Class<?> getObjectType() {
return null;
}

@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
package com.leo.spring5.collectiontype;

// 课程类
public class Course {
private String cname;

public void setCname(String cname) {
this.cname = cname;
}

@Override
public String toString() {
return "Course{" +
"cname='" + cname + '\'' +
'}';
}
}

三、配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<bean id="myBean" class="com.leo.spring5.factorybean.MyBean">

</bean>
</beans>

四、测试

package com.leo.spring5.testdemo;

import com.leo.spring5.collectiontype.Course;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {

@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
Course course = context.getBean("myBean", Course.class);
System.out.println(course);
}
}

五、执行结果

Spring5 工厂Bean_xml