接受参数的构造方法-定义为普通对象还是Spring bean? [英] Constructor that takes arguments - Define as ordinary object or spring bean?

查看:283
本文介绍了接受参数的构造方法-定义为普通对象还是Spring bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个带有构造函数的类,该构造函数带有一个或多个参数.我们还要说,这些参数应该是用户的某种输入.即,仅在运行时无法在编译时或配置时知道该参数.我应该将我的类定义为原型Spring bean,还是应该使用"new"创建它.

Let's say that I have a class with a constructor that takes one or more arguments. Let's also say that the arguments are expected to be som kind of input from the user. I.e the argument can not be known at compile-time or config-time, only at runtime. Should I define my class as a prototype spring bean or should I just create it with "new".

如果我应该将其定义为bean,如何传递参数?

If I should define it as a bean, how can I pass in the arguments?

推荐答案

在Spring中这是有问题的.如果您的类对其他bean没有依赖性,则只需使用new创建它.如果您有一个依赖于其他Spring Bean的类,但仍然希望传递一些运行时参数,那么当前Spring不支持它.

This is problematic in Spring. If your class has no dependencies on other beans, just create it with new. If you have a class depending on other Spring beans but still you want pass some runtime arguments, currently Spring does not support it.

但是请查看 SPR-7431

However have a look at SPR-7431 and my article about passing custom argument to <lookup-methods/>. If all goes well, this feature should be part of Spring 3.2 and it should match your requirements. It basically allows creating prototype-scoped beans while still passing some constructor argument.

这篇关于接受参数的构造方法-定义为普通对象还是Spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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