Spring 的 NumberFormat 线程安全
NumberFormat JavaDoc 说:
数字格式通常不同步。建议为每个线程创建单独的格式实例。
我想获取一个在我的对象中使用的实例。每个线程一个实例,或每个对象一个实例(对象不在线程之间共享)。目前该对象有一个包含 NumberFormat 的实例变量。
private NumberFormat nFormat = NumberFormat.getInstance(Locale.ITALY);
这已经很好了,我不应该有任何竞争条件,因为对象不是共享的。
但是,我不知道如何使用 Spring 来配置它,我知道 factory-method
,但我不知道如何将 Locale 传递给它。
<bean factory-method="getInstance" class="java.text.NumberFormat"
scope="prototype" />
如何正确声明我的 NumberFormat bean?
NumberFormat JavaDoc says:
Number formats are generally not synchronized. It is recommended to create separate format instances for each thread.
I want to obtain an instance to use in my objects. One instance per thread, or one instance per Object (objects are not shared among threads). At the moment the object has an instance variable containing NumberFormat.
private NumberFormat nFormat = NumberFormat.getInstance(Locale.ITALY);
This is already fine, I shouldn't have any race condition, since Objects are not shared.
However, I don't know how to use Spring to configure this, I know about factory-method
, but I don't know how to pass a Locale to it.
<bean factory-method="getInstance" class="java.text.NumberFormat"
scope="prototype" />
How to declare my NumberFormat bean properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是你可以做到的:
但是,我可能根本不会使用 Spring 来做到这一点,我会使用静态工厂方法。
This is how you could do it:
However, I probably wouldn't use Spring at all to do it, I'd use a static factory method instead.
我认为你可以使用:
constructor-arg元素用于传递构造对象所需的bean和值。另请参见 依赖注入示例了解更多信息:)
I think you can use:
constructor-arg element is used to pass beans and values that is needed to construct the object. See also Examples of dependency injection for more info :)