Spring Service中的实例变量

时间:2016-04-07 11:06:54

标签: java spring caching dictionary

我有以下Spring Service

@Service
class FeatureTogglesImpl implements FeatureToggles {

    private final FeatureToggleRepository featureToggleRepository;
    private       Map<String, Feature>    featuresCache;

    @Autowired
    public FeatureTogglesImpl(final FeatureToggleRepository featureToggleRepository) {
        this.featureToggleRepository = featureToggleRepository;
        this.featuresCache = loadAllFromRepository();
    }

    @Override
    @Transactional
    public void enable(Feature feature) {
        Feature cachedFeature = loadFromCache(feature);
        cachedFeature.enable();
        featureToggleRepository.save(cachedFeature);
        onFeatureToggled();
    }


    @Override
    public boolean isEnabled(Feature feature) {
        return loadFromCache(feature).isEnabled();
    }

    private Feature loadFromCache(Feature feature) {
        checkNotNull(feature);
        return featuresCache.get(feature.getKey());
    }

    private Map<String, Feature> loadAllFromRepository() {
        return Maps.uniqueIndex(featureToggleRepository.findAll(), new Function<Feature, String>() {
            @Override
            public String apply(Feature feature) {
                return feature.getKey();
            }
        });
    }

    void onFeatureToggled() {
        featuresCache = loadAllFromRepository();
    }

}

正如您所看到的,我将加载的功能存储到featuresCache中,以便在客户端调用isEnabled()时根据缓存中的功能加载。

有一个托管bean,负责切换功能,

@Component
@ManagedBean
@Scope("view")
public class FeatureTogglesManager {

    @Autowired
    private FeatureToggles featureToggles;

    @Secured({"ROLE_FEATURE_TOGGLES_EDIT"})
    public String enable(Feature feature) {
        featureToggles.enable(feature);
        return null;
    }

}

当我从enable()拨打AdminFeatureTogglesManager时,我可以看到切换正确的功能,并预先填充缓存。

我有另一项服务,实际上使用FeatureToggles.isEnabled()服务

@Service
class ProductServieImpl implements ProductService {

    @Autowired
    private FeatureToggles featureToggles;

    @Override
    @Transactional
    public void loadProducts() {
        if (featureToggles.isEnabled(NewProducts.insance())) {
            loadNewProducts();
            return;
        }
        loadOldProducts();
    }
}

问题是来自此服务的featureToggles.isEnabled()总是从缓存中返回旧实例,当我调试FeatureTogglesImpl时,我没有看到预先填充的缓存,尽管在切换后我可以看到正确/更新缓存。

FeatureTogglesImpl不应该是一个单一的,所以如果我改变实例变量,它会随处变化吗?任何帮助表示赞赏。

0 个答案:

没有答案