如何动态地将参数传递给Spring bean [英] How to pass parameters dynamically to Spring beans

查看:345
本文介绍了如何动态地将参数传递给Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring的新手。

I am new to Spring.

这是bean注册的代码:

This is the code for bean registration:

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

这是我的bean类:

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
}

现在我想打电话这个带有参数的构造函数,这些参数是在我的main方法中动态生成的。这就是我想要动态传递的意思 - 不是静态传递,就像在我的 bean.config 文件中声明一样。

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.

推荐答案

请看构造函数注入

另外,看看 IntializingBean BeanPostProcessor 用于其他生命周期拦截springbean。

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

这篇关于如何动态地将参数传递给Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆