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);
}

Zong
7 声望0 粉丝