menu
書いてる野郎
orebike@gmail.com
業務ロジックをまとめるためのレイヤーである Service層をどう実装するのかという話。
このように普通のクラスに Service アノテーションをつければよい
import org.springframework.stereotype.Service; @Service public class HogeService { public String hello() { return "hello hello hello"; } }
特に配置上の制限は無いのだが、service とかいうパッケージにまとめておいたほうがよいだろう。
DI してもらってそれを使うのだが、Spring Boot ではコンストラクタインジェクションを使うのがセオリーのようだ。
@RestController public class HelloController { private final HogeService hogeService; public HelloController(HogeService hogeService) { this.hogeService = hogeService; } @RequestMapping("/") public String index() { return "Hello -- " + hogeService.hello(); } }
このようにテストする。
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment=WebEnvironment.NONE) public class HogeServiceTest { @Autowired private HogeService hogeService; @Test public void helloTest() throws Exception { System.out.println("start hello test"); Assert.assertTrue("hello hello hello".equals(hogeService.hello())); System.out.println("end hello test"); } }
テスト対象がコンストラクタインジェクションされていないのは、テストクラスはコンストラクタが1つかつパラメータが無いものじゃないといけないからである。