Wednesday, 17 July 2019

Instantiating beans

Once If we create a bean, then we wanted to use in our class we need to follow some way because of which it gets initiated, after that we can use it in our application.

There are three way We can initiate the bean.

1. Instantiation with a Constructor.

In My previous posts, if you see that it is initated with the constructor. As soon we mention the bean in the defintion file and no constructor defined it will considers it as the default constructor with no arguments and initailizes it.Simply specifying the bean class should suffice. However, depending on what type of IoC you use for that specific bean, you may need a default (empty) constructor.
This will not get initialized when you define any constructor apart from the default, inorder to handle this situation, we can see in the upcoming posts.

We will get the below error when try to run.

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.searchendeca.application.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.searchendeca.application.HelloWorld.<init>()

If I define the default constructor then it started working. When means to initialize we require the default constructor.

eg:<bean id="helloWorldService"class="com.searchendeca.application.HelloWorld">
</bean>

2. Instantiation with a static factory method

When defining a bean that you create with a static factory method, you use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method itsel
eg:

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

3.Instantiation using an instance factory method

This is similar to the static factory method but here you will not mention the class and define the factory-bean attribute which has the method defined.

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

One factory class can also hold more than one factory method.

No comments:
Write comments