好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring IOC容器FactoryBean工厂Bean实例

前言

之前提到的 bean 是我们自己创建的,属于普通类型的 bean。还有一种是工厂 bean,属于 spring 中内置的一种类型。

区别是什么?以此配置为例:

?

1

2

3

< bean id = "course2" class = "com.pingguo.spring5.collectiontype.Course" >

         < property name = "course_name" value = "毛氏面点课" ></ property >

     </ bean >

普通 bean:这里 class 中定义了类型是 Course ,那么返回的类型就是 Course 。工厂 bean:对于工厂 bean来说,返回的类型可以和定义的类型不同。

工厂 bean

分两步走:

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package com.pingguo.spring5.factorybean;

import com.pingguo.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.setCourseName( "spring基础课程" );

         return course;

     }

     @Override

     public Class<?> getObjectType() {

         return null ;

     }

     @Override

     public boolean isSingleton() {

         return false ;

     }

}

可以看到,虽然类中我定义的是 MyBean 类型,但是可以在实现接口的方法 getObject() 里返回的却是 Course 类型(这里要用到泛型类,加上 FactoryBean )。

新建一个 bean3.xml配置文件:

?

1

2

3

4

5

6

<? xml version = "1.0" encoding = "UTF-8" ?>

< beans xmlns = "http://HdhCmsTestspringframework.org/schema/beans"

        xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

        xsi:schemaLocation = "http://HdhCmsTestspringframework.org/schema/beans http://HdhCmsTestspringframework.org/schema/beans/spring-beans.xsd" >

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

</ beans >

然后在测试类中继续新增一个测试方法,看下效果:

?

1

2

3

4

5

6

7

@Test

     public void test3() {

         ApplicationContext context =

                 new ClassPathXmlApplicationContext( "bean3.xml" );

         Course course = context.getBean( "myBean" , Course. class );

         System.out.println(course);

     }

运行测试,查看结果:

?

1

2

Course{course_name='spring基础课程'}

Process finished with exit code 0

以上就是Spring IOC容器FactoryBean工厂Bean实例的详细内容,更多关于Spring IOC容器FactoryBean的资料请关注其它相关文章!

原文链接:https://blog.csdn.net/wessonlan/article/details/124812984

查看更多关于Spring IOC容器FactoryBean工厂Bean实例的详细内容...

  阅读:16次