spring學習之bean的靜態工廠實例化

靜態工廠實例化

factory的配置以下: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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--clientService這個bean是由ClientService類的createInstance方法建立的-->
    <bean id="clientService" class="com.learn.ch1.ClientService" factory-method="createInstance"/>

    <bean id="serviceLocator" class="com.learn.ch1.DefaultServiceLocator"/>

    <!--clientService2這個bean是由惟一標識是serviceLocator的bean的createClientServiceInstance方法建立的-->
    <bean id="clientService2" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>
    <bean id="clientService3" factory-bean="serviceLocator" factory-method="createClientServiceInstance2"/>
</beans>

ClientServiceapp

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        System.out.println("createInstance");
        return clientService;
    }
}

DefaultServiceLocator測試

public class DefaultServiceLocator {
    public ClientService createClientServiceInstance() {
        System.out.println("createClientServiceInstance");
        return ClientService.createInstance();
    }

    public ClientService createClientServiceInstance2() {
        System.out.println("createClientServiceInstance2");
        return ClientService.createInstance();
    }
}

測試代碼spa

@Test
public void test4() {
    ApplicationContext app = new ClassPathXmlApplicationContext("factory.xml");
    System.out.println(app.getBean("clientService"));
    System.out.println(app.getBean("clientService2"));
}

運行結果以下:
image.png
factory-method用於指定實例化的靜態方法,factory-bean用於指定哪一個bean,能夠與bean的類解耦,更近靈活。若是是註解的話,那更簡單了,直接在@bean裏調用方法就好,這邊不演示了。3d

相關文章
相關標籤/搜索