Singleton in Spring to avoid reinvent wheels

来源:互联网 发布:京东java在线笔试题 编辑:程序博客网 时间:2024/05/14 09:27

Sometimes you run into below piece of code which would call a object to do something, it costs some effort to actually construct the new object every time you invoke this caller method, so to avoid this, you can actually make this object as a singleton if it's thread safe and no other conflicts.


    private void doSomething(String param) {        //....        serviceProxy.doSomethingForCaller(param);    }

Spring.xml

    <bean id="serviceProxy" class="service.ServiceProxyImpl">        <constructor-arg index="0" value="${host}"/>        <constructor-arg index="1" value="${port}"/>    </bean>

or you can create a factory method which is responsible for creating the object.

    <bean id="hongKongTimeZone" class="java.util.TimeZone" factory-method="getTimeZone">        <constructor-arg value="Asia/Hong_Kong"/>    </bean>



原创粉丝点击