简体   繁体   中英

How to refactor static functions for dependency injection?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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