spring学习之bean的静态工厂实例化

静态工厂实例化

factory的配置如下:




    
    

    

    
    
    

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

运行结果如下:

factory-method用于指定实例化的静态方法,factory-bean用于指定哪个bean,可以与bean的类解耦,更近灵活。如果是注解的话,那更简单了,直接在@bean里调用方法就好,这边不演示了。

你可能感兴趣的:(spring,java)