Open26

Spring初学メモ

KumaoKumao

コンポーネント・スキャンの対象にするためのアノテーション

アノテーション 説明
@Controller Web MVC フレームワークである、Spring MVCのコントローラであることを示すアノテーション。
Spring4からはREST Webサービス用に、@RestControllerも追加された。
@Service サービスクラスであることを示すアノテーション。
@Componentと機能的な違いはない。
@Repository リポジトリクラスであることを示すアノテーション。
このアノテーションを付けたクラス内で発生した例外は、特例のルールにしたがって、Springが提供するDataAccessExceptionに変換される。
KumaoKumao

Entity(JPA Entity)とは
データベースにおける表の個別の行に対応するオブジェクト。
PAではPOJO(Plain Old Java Object、ごく普通のJavaオブジェクト)にアノテーションを加えるだけで作成できる。
【参考】https://teachingprogramming.net/archives/145

KumaoKumao

Lombokで @Dataをつけると、getter/setterだけでなくToStringも一緒に付与してくれる。
よって関連テーブルがある場合に、ToStringが呼ばれると循環参照が発生する場合がある。

解決策
参照しないようにフィールドの出力を除く

@ToString(exclude = "customers")
KumaoKumao

lombokの@Dataについてもっと知りたい

公式より引用

@Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together

つまり@Getter/@Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructorを、アノテーションをつけるだけでよしなに作ってくれるもの…らしい。

【参考】https://projectlombok.org/features/Data

KumaoKumao

「認可用のロール作成には、AuthorityUtilsを使うと便利」…これはなんで?

まずはAuthorityUtilsのコードを見る。

 // Failed to get sources. Instead, stub sources have been generated by the disassembler.
 // Implementation of methods is unavailable.
package org.springframework.security.core.authority;
public final class AuthorityUtils {
  
  public static final java.util.List<org.springframework.security.core.GrantedAuthority> NO_AUTHORITIES;
  
  private AuthorityUtils() {
  }
  
  public static  java.util.List<org.springframework.security.core.GrantedAuthority> commaSeparatedStringToAuthorityList(java.lang.String authorityString) {
    return null;
  }
  
  public static  java.util.Set<java.lang.String> authorityListToSet(java.util.Collection<? extends org.springframework.security.core.GrantedAuthority> userAuthorities) {
    return null;
  }
  
  public static  java.util.List<org.springframework.security.core.GrantedAuthority> createAuthorityList(java.lang.String... authorities) {
    return null;
  }
  
  static {} {
  }
}

何やらリストを作ってるようだけど、これはspring securityについてもっと知らないと読めない。

ということでspring securityも調べる。
→ 仕組みは以下からなんとなく理解した。
【参考】http://terasolunaorg.github.io/guideline/current/ja/Security/Authorization.html

KumaoKumao

spring security内にあるGrantedAuthorityが、疑問の肝のような気がしてきたのでこれを調べた。

GrantedAuthority オブジェクトは AuthenticationManager によって Authentication オブジェクトに挿入され、あとで AccessDecisionManager によって認可の決定を行うときに読み取られます。
https://spring.pleiades.io/spring-security/site/docs/5.2.8.RELEASE/reference/html/authorization.html#authz-authorities

うーん。。。わかるようなわからないような。。
多分自分の中で言語化ができてない

KumaoKumao

Think of a GrantedAuthority as being a "permission" or a "right". Those "permissions" are (normally) expressed as strings (with the getAuthority() method). Those strings let you identify the permissions and let your voters decide if they grant access to something.
You can grant different GrantedAuthoritys (permissions) to users by putting them into the security context. You normally do that by implementing your own UserDetailsService that returns a UserDetails implementation that returns the needed GrantedAuthorities.

GrantedAuthority = 認可をするためのメソッド(?)
https://stackoverflow.com/questions/19525380/difference-between-role-and-grantedauthority-in-spring-security

KumaoKumao

一旦これでclose.
もし不足・不備があれば都度修正する。

KumaoKumao

Beanって何だ?

@Beanと書いたメソッドでインスタンス化されたクラスがシングルトンクラスとしてDIコンテナに登録される。任意のクラスで@Autowiredで注入してアクセスできる。

シングルトン、DIコンテナ、アクセスのように単語でしか頭に入ってなかったが、文章化された…感謝。
https://dev.classmethod.jp/articles/springboot-what-is-bean/

KumaoKumao

コンポーネント・スキャンって何だ?

コンポーネントスキャンとは
Bean定義用のアノテーションが付与されたクラスをDIコンテナに登録すること。
Bean定義用のアノテーションとは、@Component, @Controller, @Serviceといったアノテーションのこと
コンポーネントスキャンでは、Bean定義用のアノテーションが付与されたクラスを、
文字通り「スキャン」して探し、該当する各クラスをBeanとしてDIコンテナ管理下に置く処理を行います。

アノテーションをつけると、スキャンして付与されたクラスを探す。該当したクラスをBeanとしてDIコンテナ管理下に置く…ってことかな???

KumaoKumao

spring securityのconfigureの中を細かく見る

// 1. ログインフォーム以外には認証なしでアクセス不可
// 2. ログインフォームの表示パス, login, success時の遷移先、失敗時の遷移先を設定
// 3. パラメーター名を設定
// 4. ログアウトの設定
http.
authorizeRequests().antMatchers("/loginForm").permitAll().anyRequest().authenticated().and().formLogin()
        .loginProcessingUrl("/login").loginPage("/loginForm").failureUrl("/loginForm?error")
        .defaultSuccessUrl("/customers", true).usernameParameter("username").passwordParameter("password").and()
        .logout()
        .logoutSuccessUrl("/loginForm");
KumaoKumao

パスワードのハッシュ化

PasswordEncoderの実装を選ぶことで、ハッシュ化アルゴリズムを決める。以下はパスワードのハッシュ化において推奨されているPbkdf2アルゴリズムを実装。

@Bean
  PasswordEncoder passwordEncoder() {
    return new Pbkdf2PasswordEncoder();
  }
KumaoKumao

spring

  • spring boot :複雑な手順や設定なしにspringプロジェクトを作成できる
  • spring framework: webアプリのコアな機能を提供する
  • spring data: O/Rマッピングの自動化などデータベース操作を簡略化する
  • spring security: ログイン認証やCSRF対策など
KumaoKumao

POJO
普通のJavaオブジェクト
昔はある手続きをするのに何かのクラスを継承するなど複雑な手続きが必要だった。そうではないクラスのことを示す。

KumaoKumao
  • スタック領域
    インスタンスのアドレスやデータ型が保存される
  • ヒープ領域
    データの中身を保存している。ヒープ領域を見に行くことを参照する、という。
KumaoKumao

シングルトンクラス
普通クラスオブジェクトは複数のインスタンスオブジェクトを作成することができるが、一つのインスタンスを共有すれば良い場合にこのシングルトンクラスを使用する。
これを使うことで一つのインスタンスオブジェクトしか生成できなくなる。

KumaoKumao

SprintにおけるModel
=リクエストスコープを管理する

リスエストスコープでは1回のリクエスト間、メモリ上にデータを保持できるため
ViewがHTMLを作る際に必要なデータを与えることができる

KumaoKumao

Intefaceはクラスを自動生成する役割もある

KumaoKumao

thymeleafとJSP、なぜthymeleafの方が使われるのか

どちらも$の記法があるが、thymeleafの方がデザイナーがthymeleafのファイルをブラウザで見た際にデフォルト値が反映され、画面が崩れない。よって分けて開発してる際には有効。
JSPタグを追加で書いていくため、デザインを邪魔する可能性がある。

KumaoKumao

Springの@Transaction

@Transaction をつけることで、自動的にトランザクションの開始、コミット、ロールバックが行われる。
しかし…

ただし、ロールバックの注意点として、非検査例外(RuntimeException及びそのサブクラス)が発生した場合はロールバックされるが、検査例外(Exception及びそのサブクラスでRuntimeExceptionのサブクラスじゃないもの)が発生した場合はロールバックされずコミットされる。

https://qiita.com/NagaokaKenichi/items/a279857cc2d22a35d0dd

KumaoKumao

ContextHolder

スレッドローカルに値を保存しておくことで、いろんなところから参照できるようにする。
TomcatなどのAPサーバはリクエストごとにworkerスレッドを割り当てるので、@AsyncやExecutorServiceを利用して別スレッドでXXXContextHolderを利用しない限り、どこからでもスレッドローカルに登録した同じ値を参照できる。
https://www.kimullaa.com/entry/2017/02/18/211448