关于spring:Spring中的工厂Bean

0次阅读

共计 475 个字符,预计需要花费 2 分钟才能阅读完成。

Spring 中有两种 bean 类型,一般 bean 和工厂 bean
一般 bean:定义的类型和返回的类型统一
工厂 bean:定义的类型和返回的类型能够不统一
工厂 bean 的实现:
实现 FactoryBean 接口中的 getObject 办法,如

public class MyBean implements FactoryBean<Course>{public Course getBean(){Course course = new Course();
    course.setName("语文");
    return course;
  }
}

xml 创建对象

<bean id="myBean" class="com.zong.spring.MyBean"></bean>

测试

public void test(){ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
  Course course = context.getBean("myBean",Course.class);
  System.out.println(course);
}
正文完
 0