简体   繁体   English

如何只将值传递给java方法一次?

[英]How to pass value to a java method only once?

Let's say i have a java method:假设我有一个 java 方法:

private String (StringUtility stringUtil)
{
   String maxValue = stringUtil.getMaxValue()
}

Now, the StringUtility holds the maxValue and read it from configuration field loaded by Spring and won't be changed during run time .现在, StringUtility 持有 maxValue 并从 Spring 加载的配置字段中读取它,并且不会在运行时更改 this method is going to be called every 1ms.此方法将每 1 毫秒调用一次。 So, if the maxVlue won't be changed once it was loaded, is there another way to pass it to the method instead to get it every time we call the method and avoid a load when calling the stringUtil every time just to get the maxValue?因此,如果 maxVlue 在加载后不会更改,是否有另一种方法将其传递给方法,而不是在每次我们调用该方法时获取它,并避免每次调用 stringUtil 时加载只是为了获取 maxValue ?

Thank you.谢谢你。

This sounds like a good fit for a singleton you load at the start of your app and then reuse the values.这听起来很适合您在应用程序开始时加载然后重用这些值的单例。

Something like that:类似的东西:

public final class StringUtility {
    private static String maxValue;
    public static final synchronized String getMaxValue(){
        if(maxValue == null){
            //set value
        }
        return maxValue;
    }
}

Then use it in your method.然后在你的方法中使用它。

Since you're using Spring, why not make StringUtility cache values?既然您使用的是 Spring,为什么不制作StringUtility缓存值呢? You can accomplish this using Spring Cache annotations .您可以使用Spring Cache annotations完成此操作。

Depending on how your bean is described, you can do this:根据您的 bean 的描述方式,您可以执行以下操作:

@Component
public class StringUtility {

    @Value("${maxValue}")
    private String maxValue;

    @Cacheable("string-utility")
    public String getMaxValue() {
        return maxValue;
    }
}

I'll leave the configuration and full wiring as an exercise for the reader.我将把配置和完整接线留给读者作为练习。

(Even if you don't go the route of caching with Spring, this is the perfect use case for caches anyway. Since you're guaranteed that this value will never be evicted from the cache, you can rely on it to provide the value instead. Alternatively, this could be interpreted as a premature optimization, since the call would be cheap regardless of what you do.) (即使您不使用 Spring 进行缓存,无论如何这都是缓存的完美用例。由于您保证此值永远不会从缓存中驱逐,因此您可以依靠它来提供该值相反。或者,这可能被解释为过早优化,因为无论您做什么,调用都会很便宜。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM