【问题标题】:Why we do mark method’s parameters as final while using Elasticsearch? [duplicate]为什么我们在使用 Elasticsearch 时将方法的参数标记为 final? [复制]
【发布时间】:2022-01-31 07:51:36
【问题描述】:

我最近开始学习 Elasticsearch,已经观看了一些关于这项技术的视频,并注意到我们将方法参数中的字段标记为 final。同时,我们在使用 MySQL 时不使用 this 关键字标记参数,例如。

为什么?因为 Elasticsearch 内部没有字段锁和事务,不像 MySQL?

例如:

假设我们的应用中有一个用于用户的 REST 控制器,以及一个根据该控制器内部的 id 返回用户的方法。

在我们使用 MySQL 的情况下:

@GetMapping(“/user/{id}”)
public User getUserById(@ParhVariable Long id) {
return userRepository.getById(id).orElse(null);
}

在我们使用 Elasticsearch 的情况下:

@GetMapping(“/user/{id}”)
public User getUserById(@ParhVariable final Long id) {
return userRepository.getById(id).orElse(null);
}

【问题讨论】:

  • 你知道final关键字应用于变量时的作用吗?
  • 当然是@Sultiske

标签: java mysql elasticsearch


【解决方案1】:

它没有连接到 ElasticSearch 或 MySQL。当您将 final 关键字设置为您的 id 变量时 - 您不能在您的 getUserById 方法中为该变量分配一个新值(Long 的对象)。

它可以防止这种情况:

@GetMapping(“/user/{id}”)
public User getUserById(@ParhVariable Long id) {
    id = 10L; // new value
    return userRepository.getById(id).orElse(null); // will response with wrong entity
}

在上面的代码中,程序不会返回用户期望的值。如果您在id 变量上设置final 关键字并尝试将新值分配给id - 程序甚至不会编译,这会阻止运行时出现意外行为。

没有严格的规则总是使用final或不使用 - 最常见的方法是在代码长且复杂时使用final

还要检查this 的答案。

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 2014-01-14
    • 2018-01-22
    • 2017-10-05
    • 2012-05-14
    • 2019-09-17
    • 2016-12-28
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多