Spring (3.2.3), spring3.2.3
To create a Bean instance object, follow these steps:
- Call the constructor to create a Bean instance
- Call the static factory method to create a Bean instance
- Call the instance factory method to create a Bean instance
Use the constructor to create a Bean instance
XML configuration:
<bean id="exampleBean" class="examples.ExampleBean"/><bean name="anotherExample" class="examples.ExampleBeanTwo"/>
Create Bean instance using static factory Method
XML configuration:
<bean id="clientService" class="examples.ClientService" factory-method="createInstance"/>
Static factory class:
public class ClientService { private static ClientService clientService = new ClientService(); private ClientService() {} public static ClientService createInstance() { return clientService; }}
Create a Bean instance using the instance factory Method
XML configuration:
<!-- 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"/>
Instance factory type:
public class DefaultServiceLocator { private static ClientService clientService = new ClientServiceImpl(); private DefaultServiceLocator() {} public ClientService createClientServiceInstance() { return clientService; }}