Spring实例化bean的几种方式

一,通过constructor实例化bean

Spring可以实例化各种类型的类,不要求必须是JavaBean类型的类。在XML中配置类如下:

  

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

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

二,通过静态factory method实例化bean

当通过静态factory method实例化bean时,需要用class属性来指定含有静态factory method的类,用factory-method属性来指定对应的factory method。当调用这一方法时,将返回一个类的对象,效果和通过constructor来实例化相同。注意,对应的factory method必须是static方法。

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

三,通过实例factory method来实例化bean

与通过静态factory method实例化bean的方法类似,区别是,通过实例factory method来实例化bean需要调用容器中另一个bean的非静态方法。使用这种方式时,class属性不需要填写,在factory-bean属性中制定容器中包含指定factory method的bean,在factory-method属性中设置factory method的名称。

<!-- 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;
    }
}

一个factory类可以包含多个factory method。

<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</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;
    }

}

 

posted on 2016-07-29 10:13  孜然狼  阅读(2745)  评论(0编辑  收藏  举报

导航