1. (C) CASAREAL, Inc. All rights reserved.
Pivotal認定講師が解説!
初めてでも30分で分かる
Spring 5 & Spring Boot 2
オーバービュー
(株)カサレアル 多⽥真敏
2018年6⽉28⽇
1
2. (C) CASAREAL, Inc. All rights reserved.
このセッションについて
▸ Spring 5・Spring Boot 2とはどんなものか、
基礎から分かりやすく解説します
▸ 【初級者向け】ある程度Javaの経験があり、
Springは初めての⽅が対象です
2
3. (C) CASAREAL, Inc. All rights reserved.
⾃⼰紹介
▸ 多⽥真敏(@suke_masa)
▸ 研修トレーナー@カサレアル
▸ Spring / Java EE / Microservices
/ Cloud Foundry
▸ Pivotal認定講師
▸ ⽇本Springユーザ会スタッフ
▸ ⽇本GlassFishユーザー会運営メンバー
3
4. (C) CASAREAL, Inc. All rights reserved.
Thymeleaf 3のドキュメントを(ちょっと)和訳しました!
4
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf_ja.html
5. (C) CASAREAL, Inc. All rights reserved.
株式会社カサレアル
▸ 他社には無い⾊々なプログラミング⾔語の研修
を提供しています!
5
6. (C) CASAREAL, Inc. All rights reserved.
世界⼀ハイレベルなSpring研修
▸ Pivotal認定 Core Spring (4⽇間)
▸ DI、AOP、Test、JDBC、Tx、Data、Boot、Web、
Security、REST、Microservices、Reactive
▸ ロジカルな講義+演習で徹底理解
▸ アーキテクトやリーダー向け
▸ もちろんSpring 5に対応!
6
https://www.casareal.co.jp/ls/service/openseminar/pivotal/p016
7. (C) CASAREAL, Inc. All rights reserved.
エントリー向けSpring研修
▸ はじめてのSpring MVCによる
Webアプリケーション開発 (2⽇間)
▸ Web、Thymeleaf、Bean Validation、例外処理、
JDBC、REST、Boot(、付録でMyBatis)
▸ 初⼼者〜チームメンバー向け
▸ もちろんSpring 5に対応!
7
https://www.casareal.co.jp/ls/service/openseminar/java/j040
8. (C) CASAREAL, Inc. All rights reserved.
Spring Securityを完全マスター
▸ Spring Security⼊⾨ (1⽇間)
▸ Spring Security 5の基礎から
OAuth 2.0までを演習中⼼で学習
▸ 複雑と⾔われるSpring Securityの
アーキテクチャーも完全解説!
▸ チームメンバー〜アーキテクトまで
幅広いレベルに対応!
8
https://www.casareal.co.jp/ls/service/openseminar/java/j120
9. (C) CASAREAL, Inc. All rights reserved.
⽬次
9
1. Core
3. Web
2. Data
4. Security
5. Test
6. Boot
10. (C) CASAREAL, Inc. All rights reserved.
⽬次
10
1. Core
3. Web
2. Data
4. Security
5. Test
6. Boot
11. (C) CASAREAL, Inc. All rights reserved.
Springとは
▸ いろんなフレームワークの集合体
▸ DI/AOP、Web、Data、Security、Test、Boot、
Cloud、・・・
▸ 現在はPivotal社が中⼼となりオープンソースで開発
▸ 元々はRod Johnson⽒が開発したもの
▸ 最新はSpring 5(2017年9⽉リリース)
11
12. (C) CASAREAL, Inc. All rights reserved.
Spring 5はJDK 8ベース
▸ JDK 8の機能が、Spring 5内部でも公開APIでも
使われている
▸ Date and Time API、ラムダ式、Stream API、
Optional、インタフェースのデフォルトメソッド、
メソッド引数名による解決、など
▸ JDK 7未満では動かない!!!😖
12
13. (C) CASAREAL, Inc. All rights reserved.
JDK 9/10対応
▸ Spring 5はJDK 9/10上でも動作保証済み!
▸ JDK 9のモジュールシステムにも対応👏
▸ JDK 11上でも動く予定
▸ JDK 11は2018年9⽉リリース予定
(LTS : Long Term Support)
13
14. (C) CASAREAL, Inc. All rights reserved.
Springの根幹「DI」
▸ Dependency Injection(依存性の注⼊)
▸ 必要なインスタンス(=依存性)を外から代⼊すること
▸ テスト時のインスタンスの差し替えなどが可能になる
14
objA
objB
objA
objB代⼊
new
⭕❌
15. (C) CASAREAL, Inc. All rights reserved.
DIコンテナ
▸ Springが内部で持ってい
るインスタンス(Bean)
の格納庫
▸ すべてのBeanはDI済み
になっている※
▸ 必要に応じて取り出し可
能
15
DIコンテナ
BeanBean Bean
Bean Bean Bean
Bean Bean
DI DI
DIDI
DI
D
I
※デフォルトでは起動時に全てのBeanがインスタンス化&DIされる
16. (C) CASAREAL, Inc. All rights reserved.
Beanを定義する⽅法①
▸ コンポーネントスキャン
▸ クラスに@Componentを
付加
▸ Java Configクラスに上記
クラスのパッケージ名を
指定
16
package com.service;
@Component
public class HelloService {
// omitted…
}
@Configuration
@ComponentScan(basePackages
= "com.service")
public class ServiceConfig {
// omitted…
}
17. (C) CASAREAL, Inc. All rights reserved.
正体が@Componentなアノテーション
▸ @Controller
▸ @RestController
▸ @Service
▸ @Repository
▸ @Configuration
・・・他にもいろいろ
▸ これらは「ステレオタイプアノテーション」と呼ばれる
17
18. (C) CASAREAL, Inc. All rights reserved.
Beanを定義する⽅法②
▸ Java Configにメソッ
ドを作成し@Beanを
付加
▸ 戻り値がBeanにな
る
▸ メソッド引数で他の
Beanを受け取れる
▸ ①と②は併⽤可能
18
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
return new HogeDataSource();
}
@Bean
public JdbcTemplate jdbcTemplate(
DataSource ds) {
return new JdbcTemplate(ds);
}
}
19. (C) CASAREAL, Inc. All rights reserved.
DI
▸ @Autowiredで他のBeanを外から代⼊できる
▸ コンストラクタが1つのみの場合は省略可能
19
@Controller
public class HelloController {
private final HelloService service;
@Autowired // 省略可能
public HelloController(HelloService svc) {
this.service = svc;
}
// omitted...
}
@Service
public class HelloService {
// omitted...
}
20. (C) CASAREAL, Inc. All rights reserved.
Webアプリケーションの3層アーキテクチャー
20
View
Controller Service Repository
DB
プレゼンテーション層
ビジネス
ロジック層
永続化層
リクエスト
レス
ポンス
21. (C) CASAREAL, Inc. All rights reserved.
3層アーキテクチャーとDI
21
Controller Service RepositoryDIDI
22. (C) CASAREAL, Inc. All rights reserved.
⽬次
22
1. Core
3. Web
2. Data
4. Security
5. Test
6. Boot
23. (C) CASAREAL, Inc. All rights reserved.
Springのデータアクセス技術
▸ Spring JDBC
▸ JDBCの単純なラッパー
▸ Spring Data
▸ 様々なデータアクセスを共通化(JPA、Redis、MongoDB等)
▸ その他、各種ORマッパーがSpring連携機能を提供
▸ MyBatis、DBFlute等
23
24. (C) CASAREAL, Inc. All rights reserved.
Spring Data JDBC (ベータ版)
▸ Spring JDBCを利⽤したSpring Data
▸ MyBatisも利⽤可能
24
// インタフェースを作るだけ!
public interface EmployeeRepository
extends CrudRepository<Employee, Long> {
// アノテーションにSQLを書ける
@Query("SELECT ... FROM employee WHERE hoge = :hoge")
List<Employee> findByHoge(String hoge);
// CrudRepositoryのメソッドは全て使える パラメータ名を揃える※
※コンパイル時(javac)のオプションに「-parameters」が必要
36. (C) CASAREAL, Inc. All rights reserved.
コントローラー
36
@Controller
public class EmployeeController {
private final EmployeeService service;
@Autowired // 省略可能
public EmployeeController(EmployeeService service) {
this.service = service;
}
@GetMapping("/")
public String index(Model model) {
Iterable<Employee> employees = service.findAll();
model.addAttribute("employees", employees);
return "index";
}
}
コントローラーとしてBean定義
ビジネスロジックをDI
メソッドとURLをマッピング
値をビューに渡す
ビューのパスの⼀部を返す
37. (C) CASAREAL, Inc. All rights reserved.
必要なBean定義
37
@ComponentScan(basePackages =
"com.example.web.controller")
@EnableWebMvc
@Configuration
public class MvcConfig ... {
...
@Bean
public ThymeleafViewResolver
viewResolver(...) {
...
}
...
}
▸ ViewResolver
をBean定義する
▸ コントローラーク
ラスをコンポーネ
ントスキャン
▸ @EnableWebMvc
を付加
38. (C) CASAREAL, Inc. All rights reserved.
その他の機能
▸ ⼀通りの機能が揃っている
▸ ⼊⼒検証(Bean Validation連携)
▸ 例外処理
▸ ファイルアップロード
▸ RESTful Webサービス
・・・など
38
39. (C) CASAREAL, Inc. All rights reserved.
⽬次
39
1. Core
3. Web
2. Data
4. Security
5. Test
6. Boot
40. (C) CASAREAL, Inc. All rights reserved.
Spring Securityとは
▸ 主に認証・認可の機能を提供するセキュリティ
ライブラリ
▸ 何重ものサーブレットフィルターや、
AOP(割り込み処理)を使って、
ログインや権限チェックを⾏う
40
41. (C) CASAREAL, Inc. All rights reserved.
web.xmlへのフィルター設定
41
<web-app>
...
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
これだけで⼗数個のフィルターが動く!
42. (C) CASAREAL, Inc. All rights reserved.
認証・認可の設定
42
@EnableWebSecurity
public class SecurityConfig
extends WebSecurityConfigurerAdaptor {
@Override
protected void configure(HttpSecurity http) ... {
http.formLogin() // ログイン画⾯の設定
.loginPage("/login")
.permitAll();
http.authorizeRequests() // URLごとの権限設定
.mvcMatchers("/admin*").hasRole("ADMIN")
.anyRequest().authenticated();
http.logout() // ログアウトの設定
.permitAll();
}
...
}
43. (C) CASAREAL, Inc. All rights reserved.
PasswordEncoder
▸ DB等にはパスワードをハッシュ化して保存する
▸ ⼊⼒されたパスワードは、ハッシュ化してからDBのパ
スワードと照合する
43
@EnableWebSecurity
public class SecurityConfig
extends WebSecurityConfigurerAdaptor {
...
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
44. (C) CASAREAL, Inc. All rights reserved.
thymeleaf-extras-springsecurity
▸ Thymeleafが提供している、Spring Securityと
連携するためのライブラリ
▸ 認証や権限の有無などで表⽰/⾮表⽰を切り替え
ることができる
44
<!--/* ADMINロールのみ下記のリンクを表⽰する */-->
<a th:href="@{/admin}" sec:authorize="hasRole('ADMIN')">
管理画⾯へ
</a>
45. (C) CASAREAL, Inc. All rights reserved.
⽬次
45
1. Core 2. Web
3. Data4. Security
5. Test
6. Boot
46. (C) CASAREAL, Inc. All rights reserved.
Spring Testとは
▸ JUnitやTestNGと、Springを連携させるライブ
ラリ
▸ Spring 5でJUnit 5に対応!👏
▸ その他、Spring MVCやDBを利⽤したテストの
機能も提供
46
47. (C) CASAREAL, Inc. All rights reserved.
JUnit 5対応
▸ SpringExtension
▸ JUnit 5上でSpringのDI機能などを使えるようにする拡
張機能
47
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = HelloTestConfig.class)
public class HelloTest {
@Autowired HelloService service;
// テストを書く…
}
48. (C) CASAREAL, Inc. All rights reserved.
テストメソッド引数でもDI可能
▸ SpringExtensionは
JUnit 5のParameterResolverを実装
48
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = HelloTestConfig.class)
public class HelloTest {
@Test
void test(@Autowired HelloService service) {
// テストを書く…
}
}
49. (C) CASAREAL, Inc. All rights reserved.
便利なアノテーション
▸ @SpringJUnitConfig
▸ @ExtendWith(SpringExtension.class)
+ @ContextConfiguration
▸ @SpringJUnitWebConfig
▸ @ExtendWith(SpringExtension.class)
+ @ContextConfiguration
+ @WebAppConfiguration
49
50. (C) CASAREAL, Inc. All rights reserved.
⽬次
50
1. Core
3. Web
2. Data
4. Security
5. Test
6. Boot
51. (C) CASAREAL, Inc. All rights reserved.
Spring Bootとは
① Auto Configurationクラス
▸ ⼤量のJava Configがあらかじめ提供済み!
② Starterライブラリ
▸ ⼤量の依存ライブラリが1つにまとめられている!
③ 組み込みサーバー⼊りFat JAR
▸ 単独で起動できる!
51
52. (C) CASAREAL, Inc. All rights reserved.
①Auto Configurationクラス
52
▸ Spring Boot
によって
Java Config
が
あらかじめ
⼤量に⽤意
されている
53. (C) CASAREAL, Inc. All rights reserved.
②Starterライブラリ
53
▸ Starterライブラ
リを指定すれば、
芋づる式に⼤量
のライブラリが
追加される
54. (C) CASAREAL, Inc. All rights reserved.
③組み込みサーバー⼊りFat JAR
54
$ jar -tvf target/04-boot2-answer-0.0.1-SNAPSHOT.jar
524 Thu Jun 21 13:27:06 JST 2018 META-INF/MANIFEST.MF
2688 Wed May 09 13:32:20 JST 2018 org/springframework/boot/loader
/data/RandomAccessDataFile$DataInputStream.class
...
607 Thu Jun 21 13:27:06 JST 2018 BOOT-INF/classes/com/example/web
/controller/LoginController.class
...
1650 Thu Jun 21 13:27:06 JST 2018 BOOT-INF/classes/com/example
/Application.class
604 Wed May 09 13:41:42 JST 2018 BOOT-INF/lib
/spring-boot-starter-security-2.0.2.RELEASE.jar
...
425493 Tue May 08 15:24:16 JST 2018 BOOT-INF/lib
/spring-security-core-5.0.5.RELEASE.jar
3115994 Fri Apr 27 21:24:52 JST 2018 BOOT-INF/lib
/tomcat-embed-core-8.5.31.jar
240244 Fri Apr 27 21:24:54 JST 2018 BOOT-INF/lib
/tomcat-embed-el-8.5.31.jar
256776 Fri Apr 27 21:24:54 JST 2018 BOOT-INF/lib
/tomcat-embed-websocket-8.5.31.jar
▸ ビルド成果物のJARに、作成したクラスやライブラリ、組み
込みサーバーなどが全て含まれている
55. (C) CASAREAL, Inc. All rights reserved.
つまり・・・
▸ 開発のセットアップが簡単にできる!😆
▸ Java Configの作成がほぼ不要に
▸ 追加するライブラリが少なくて済む
▸ 簡単に起動・デプロイできる!😆
▸ サーバーの設定の必要無し
▸ 特にクラウド向き
55
56. (C) CASAREAL, Inc. All rights reserved.
よくある勘違い🙅
▸ 開発を⾼速化できる❌
▸ Java Configはほぼ不要になるが、
機能開発する部分は⼀切変わらない
▸ Spring⾃体の知識は無くても良い❌
▸ 機能開発には変わらずSpringを利⽤する
▸ 設定は何も書かなくて良い❌
▸ Auto Configurationクラスが無いものは変わらず必要
56
57. (C) CASAREAL, Inc. All rights reserved.
main()メソッドからの起動
▸ あらかじめ⽤意された⼤量のJava Configを読み
込む
▸ 組み込みサーバーを起動する
57
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(
Application.class, args);
}
}
58. (C) CASAREAL, Inc. All rights reserved.
@SpringBootApplication
▸ 下記3つのアノテーションを組み合わせたもの
▸ @Configuration
▸ @CompomentScan
▸ @EnableAutoConfiguration
58
Auto Configurationを有効化する
59. (C) CASAREAL, Inc. All rights reserved.
おすすめスライド資料
▸ ReactiveだけじゃないSpring 5 & Spring Boot 2新機能解説
▸ https://www.slideshare.net/masatoshitada7/reactivespring-5-spring-boot-2
▸ Spring Bootの本当の理解ポイント
▸ https://www.slideshare.net/masatoshitada7/spring-boot-jjug
▸ Spring Boot Actuator 2.0 & Micrometer
▸ https://www.slideshare.net/makingx/spring-boot-actuator-20-micrometer
▸ Introduction to Spring WebFlux
▸ https://www.slideshare.net/makingx/introduction-to-spring-webflux-jsug-
sfa1
59
60. (C) CASAREAL, Inc. All rights reserved.
おすすめ書籍
▸ 改訂新版Spring⼊⾨(技術評論社)
▸ アーキテクチャーの概要を理解する
▸ Spring徹底⼊⾨(翔泳社)
▸ リファレンスとして
60
61. (C) CASAREAL, Inc. All rights reserved.
頼りになるリファレンス
▸ Terasoluna Development Guideline (⽇本語)
▸ http://terasolunaorg.github.io/guideline/5.4.1.RELEASE/ja/
▸ Spring Framework Reference (英語)
▸ https://docs.spring.io/spring/docs/current/spring-framework-reference/
▸ Spring Security Reference (英語)
▸ https://docs.spring.io/spring-security/site/docs/current/reference/
htmlsingle/
▸ Spring Boot Reference (英語)
▸ https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
61
62. (C) CASAREAL, Inc. All rights reserved.
次回の研修⽇程
▸ Pivotal認定Core Spring(4⽇間)
▸ ①7⽉5⽇〜(締切)、②9⽉10⽇〜
▸ はじめてのSpring MVCによるWebアプリケーション開発
(2⽇間)
▸ ①8⽉2⽇〜、②9⽉5⽇〜
▸ Spring Security⼊⾨(1⽇間)
▸ ①7⽉31⽇、②9⽉20⽇
62https://www.casareal.co.jp/ls/service/openseminar/top/index.html
63. (C) CASAREAL, Inc. All rights reserved.
Enjoy Spring 5 & Boot 2!!
▸ ご清聴ありがとうございました!
63