Search code examples
javaspringjavabeans

How to pass parameters dynamically to Spring beans


I am new to Spring.

This is the code for bean registration:

<bean id="user" class="User_Imple"> </bean>
<bean id="userdeff" class="User"> </bean>

and this is my bean class:

public class User_Imple implements Master_interface {

    private int id;
    private User user; // here user is another class

    public User_Imple() {
        super();
    }

    public User_Imple(int id, User user) {
        super();
        this.id = id;
        this.user = user;
    }

    // some extra functions here....
}

and this is my main method to perform action:

public static void main(String arg[]) {

    ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
    Master_interface master = (Master_interface)context.getBean("user");

    // here is my some operations..
    int id = ...
    User user = ...

    // here is where i want to get a Spring bean
    User_Imple userImpl; //want Spring-managed bean created with above params
}

Now I want to call this constructor with parameters, and these parameters are generated dynamically in my main methods. This is what I mean by I want to pass dynamically – not statically, like declared in my bean.config file.


Solution

  • Please have a look at Constructor injection.

    Also, Have a look at IntializingBean and BeanPostProcessor for other life cycle interception of a springbean.