Spring Boot/Service

業務ロジックをまとめるためのレイヤーである 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つかつパラメータが無いものじゃないといけないからである。

java/spring/spring_boot/service/start.txt · 最終更新: 2018-11-07 16:27 by ore