开发者

NumberFormat thread safety with Spring

开发者 https://www.devze.com 2023-04-12 18:57 出处:网络
NumberFormat JavaDoc says: Number formats are generally not synchronized. It is recommended to create separate format instances for each thread.

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?


This is how you could do it:

<bean id="numberFormat" factory-method="getInstance"
      class="java.text.NumberFormat" scope="prototype">
    <constructor-arg>
        <util:constant static-field="java.util.Locale.ITALY" />
    </constructor-arg>
</bean>

However, I probably wouldn't use Spring at all to do it, I'd use a static factory method instead.


I think you can use:

<bean factory-method="getInstance" class="java.text.NumberFormat" 
scope="prototype">
   <constructor-arg><ref bean="locale_bean"/></constructor-arg>
</bean>

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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号