0

We have some legacy code abusing static class variables and functions for caching. Example:

public class MetaDataCache {
    static LoadingCache<String, GcsMetadata> metadataCache;

    // initial set up on server start up
    public static void setup(Config config){
                metadataCache =
                CacheBuilder.newBuilder()
                        .refreshAfterWrite(30, TimeUnit.SECONDS)
                        .build(getCacheLoader());
    }
    
    // load and reload the cache
    private static CacheLoader<String, GcsMetadata> getCacheLoader() {}

    // access cache and get value
    public static GcsMetadata getMetaData(String key) {
        return metadataCache.get(key);
    }

}
public class Application {
    public static void main(){
        MetaDataCache.setup(config);
        MetaDataCache.getMetaData("cacheKey");
    }
}

Now I'm trying refactoring the MetaDataCache class to avoid using static functions for dependency injection with Dagger 2, what's the best approach?

Frank
  • 1,315
  • 7
  • 24
  • 43
  • Related: https://stackoverflow.com/questions/52325438/how-to-inject-dependency-to-static-class – Steven Jul 28 '21 at 00:13
  • 2
    I mean, it looks like you really should just remove the `static` keyword, provide a MetaDataCache from the Config, and inject the MetaDataCache where you need it. – Louis Wasserman Jul 28 '21 at 02:03

1 Answers1

0

It seems that what you really want is a singleton object.

Remove all the static keywords to convert it to an instance class, and annotate the class with the @Singleton scope. If you create a Component that also has the @Singleton scope, then only one instance will ever be created by said component.

MikeW
  • 36
  • 4