主に 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";
}
}