静态工厂实例化bean vs工厂在Spring中实例化bean

时间:2015-06-23 07:59:22

标签: java spring

在Spring中,我们可以使用工厂和静态工厂来实现bean的实例化。 我们应该去工厂和静态工厂的所有场景? 哪一个更好的选择在Spring中实例化bean及其优缺点?

使用静态工厂

<bean id="clientService"  class="examples.ClientService" 
 factory-method="createInstance"/>

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

public static ClientService createInstance() {
    return clientService;
}

}

使用工厂

<bean id="serviceLocator" class="examples.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->

<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>

<bean id="accountService"
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/>

public class DefaultServiceLocator {

private static ClientService clientService = new ClientServiceImpl();
private static AccountService accountService = new AccountServiceImpl();

private DefaultServiceLocator() {}

public ClientService createClientServiceInstance() {
    return clientService;
}

public AccountService createAccountServiceInstance() {
    return accountService;
}

}

0 个答案:

没有答案