【问题标题】:Should Predicates of Spring Specification be static?Spring规范的谓词应该是静态的吗?
【发布时间】:2016-01-09 15:18:42
【问题描述】:

Predicate 的弹簧 Specification 应该是静态的还是非静态的?

默认实现类似如下:

public static Specification<Customer> byCustomerName(String name) {
    return new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.equal(root.get(Customer_.name), name);
        }
    };
}

但这也可以重构为:

private static final CUSTOMER_SPEC = return new Specification<Customer>() {
    @Override
    public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        return cb.equal(root.get(Customer_.name), name);
    }
};

public static Specification<Customer> byCustomerName(String name) {
    return CUSTOMER_SPEC;
}

应该首选什么? Specifications 线程安全吗?可以这样使用吗?

【问题讨论】:

    标签: java spring hibernate spring-data-jpa jpamodelgen


    【解决方案1】:

    您重构的代码甚至无法编译。有一个多余的返回,CUSTOMER_SPEC 没有类型,你指的是一个在作用域中不存在的name 变量。

    我认为您在这里过度思考了这个问题,并且正在进行微优化。将Specification 保留在静态工厂方法中应该没问题。

    【讨论】:

      【解决方案2】:

      线程安全在这里不会成为实现的问题。您根本不保留任何状态,每个参数都由调用者传递。

      它可能是微优化的,但你的重构会很有用,例如当规范发生大量实例化时。这可能会过于频繁地触发 GC,从而导致响应速度明显滞后。

      此类微优化的缺点可能是您最终可能需要相当多的内存,因为无法对实例进行 GC。

      首先通过收集数据(分析堆……)来支持您的决定,并测试您的解决方案对应用程序的影响。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-04
        • 2022-11-21
        • 1970-01-01
        • 2011-06-23
        • 1970-01-01
        • 1970-01-01
        • 2017-07-16
        相关资源
        最近更新 更多