1. Spring有两种类型bean,一种是普通bean,另外一种工厂FactoryBean
    2. 普通bean:在配置文件中定义为bean类型就是返回类型。
    3. 工厂bean:在配置文件定义bean类型可以和返回类型不一样。

    步骤:

    1. 第一步,先创建类作为工厂bean,实现接口FactoryBean。
    2. 第二步,实现接口里面的方法,在实现的方法中定义返回的bean类型。

    xml文件

    1. <bean id="beanF" class="com.zcc.spring.service.BeanImpl"/>

    Java

    1. package com.zcc.spring.service;
    2. import com.zcc.spring.pojo.Course;
    3. import org.springframework.beans.factory.FactoryBean;
    4. /**
    5. * @author 23839
    6. */
    7. public class BeanImpl implements FactoryBean<Course> {
    8. @Override
    9. public Course getObject() throws Exception {
    10. return new Course("zcc123");
    11. }
    12. @Override
    13. public Class<?> getObjectType() {
    14. return null;
    15. }
    16. @Override
    17. public boolean isSingleton() {
    18. return false;
    19. }
    20. }

    运行

    @Test
    public void test6() {
        ApplicationContext context = new ClassPathXmlApplicationContext("xmls/BeanFirty.xml");
        Course course = context.getBean("beanF",Course.class);
        System.out.println("course.toString() = " + course.toString());
    }