Tuesday, August 12, 2014

Spring Constructing Beans

By default Spring uses no arg constructor to create the bean. Spring also employs the same way of construction object as you would do normally while creating object. So when you say

<bean id=“user” class=“User"/>

Spring uses the default constructor or a no argument constructor supplied by you. Note that for the class User to be used as a Spring bean one does not have to implement any interface. In fact User class does not even knows that it is being used by Spring.

If the User class has a static method than also you can ask spring to use the static method.


public static User createUser(){
    System.out.println("In createUser method");
    return new User();

Now to create the bean using this factory method, in configuration file

<bean id=“factoryUser” class=“User“  factory-method=“createUser” />

Fetching the object

User factoryUser = (User)appContext.getBean("factoryUser");

If the object creation logic is in another factory class than also you can ask Spring to use the factory class to create the object


public class UserFactory {
    public User createUser(){
        System.out.println("Using factory to createUser");
        return new User();

Register the factory class in Spring

<bean id="userFactory" class="UserFactory" />

Ask spring to use the factory class to create the User object

<bean id="userCreatedFromFactory“   factory-bean="userFactory"factory-method="createUser">

No comments:

Post a Comment