1

静态工厂实例化

factory的配置如下:

<?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>

ClientService

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

测试代码

@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里调用方法就好,这边不演示了。


大军
847 声望183 粉丝

学而不思则罔,思而不学则殆