Spring的FactoryBean接口

Spring的FactoryBean 接口

1 介紹

FactoryBean接口有三個待實現的方法:

  1. T getObject()
  2. Class getObjectType();
  3. boolean isSingleton();

FactryBean與普通的bean差別在於,普通bean通過ID從容器中拿到的是class註明的類對象,而FactryBean的實現類則獲取到的則是getObject()對象,其類型爲getObjectType(),這樣可以通過@Autowired實現按byType注入;

2 代碼Demo

2.1 定義一個基礎對象

public class Person {
    private String name;
    private String address;
    private String sex;
    //省略getter/setter方法
}

2.2 實現FacotryBean接口

public class SpringFactoryBean implements FactoryBean {

    @Autowired
    private Person person;

    public Object getObject() throws Exception {
        return person;
    }

    public Class<?> getObjectType() {
        return person.getClass();
    }

    public boolean isSingleton() {
        return true;
    }
}

2.3 Spring配置文件

<?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:task="http://www.springframework.org/schema/task"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 包路徑掃描 -->
    <context:component-scan base-package="spring"/>

    <bean id="person" class="common.Person">
        <property name="address" value="上海市長寧區"/>
        <property name="name" value="張三" />
        <property name="sex" value="男"/>
    </bean>

    <bean id="springFactory" class="spring.factorybean.SpringFactoryBean" />

</beans>

2.4 Junit測試代碼

public class SpringFactoryBeanTest extends AbstractTest {

    @Autowired
    private SpringFactoryBean factoryBean;

    @Test
    public void test() throws Exception{
        final Object object = factoryBean.getObject();
        final Class<?> objectType = factoryBean.getObjectType();

        System.out.println(JSON.toJSONString(object));
        System.out.println(object.getClass().getName());

    }
}

2.5 輸出結果

    {"address":"上海市長寧區","name":"張三","sex":"男"}
    common.Person

2.6 結論

實現了FactoryBean接口的類,其存在於容器中的對象是 方法getObject的對象,對象類型是由方法getType返回的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章