Spring - IoC(3): Bean 实例的创建方式

创建一个 Bean 实例对象的方法通常有如下方式:

  • 调用构造器创建 Bean 实例
  • 调用静态工厂方法创建 Bean 实例
  • 调用实例工厂方法创建 Bean 实例

 

使用构造器创建 Bean 实例

XML 配置:

<bean id="exampleBean" class="examples.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

 

使用静态工厂方法创建 Bean 实例

XML 配置:

<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 实例

XML 配置:

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>

实例工厂类:

public class DefaultServiceLocator {
    private static ClientService clientService = new ClientServiceImpl();
    private DefaultServiceLocator() {}
    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

 

posted on 2015-05-15 21:33  huey2672  阅读(327)  评论(0编辑  收藏  举报