LoginSignup
11
11

More than 5 years have passed since last update.

Spring web と組み合わせた lombok の使いどころ

Posted at

主に spring と組み合わせたときの Lombok の使い方

設定 Bean 作成

こんなコードで Property ファイルから設定を読み込んだ Immutable な Configuration Bean ができる

SampleConfiguration.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;


@lombok.Value
@PropertySource("classPath:/someprop.properties")
@Configuration
public class SimpleConfiguration {
  @Value("${prop}")
  String prop;

  @Value("${feature.enabled}")
  boolean featureEnabled;

  @Value("#{'${server.id}'.split(',')}")
  private List<Integer> serverId;
}
someprop.properties
prop=Hello, world.
feature.enabled=true
server.id=100,102,103

コントローラー定義

@Controller には,@Slf4j, @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true), @RequiredArgsConstructor(onConstructor = @__(@Autowired)) を着けると幸せになれる.@Autowired@Inject にするとよりいいっぽい.

SampleController.java
@Slf4j
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@RequiredArgsConstructor(onConstructor = @__(@Autowired /* or @Inject */))
@Controller
class SampleController {
  static String CONST_STR = "この変数は実際には private static final";

  /** 作成されたコンストラクターを使って,Spring が値を入れてくれる */
  HttpServletRequest request; // 実際には private final 変数
  XxxService xxxService;
  SampleConfiguration config;

  @RequestMapping("/home")
  public String getHome(final ModelMap modelMap) {
    if (!request.isSecure()) {
      log.info("redirect");
      return "redirect:" + request.getRequestURI();
    }

    if (config.isFeatureEnabled()) {
      modelMap.put("xxxs", xxxService.getItems());
    }

    modelMap.put("message", "Hello, world!");

    return "home.thymeleaf.xhtml";
  }
}
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11