0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

☕ SpringのBeanとは何か?〜完全に意味不明だった僕がようやく理解した記録〜

Posted at

🔍 Beanって何?

SpringにおけるBeanとは、Springコンテナによって管理されるインスタンスのこと。
主に「依存注入(DI: Dependency Injection)」の仕組みで利用される。

🧠 そもそも依存注入とは?

DIの超ざっくり説明:

  • new を使わずにインスタンスを作ってくれる
  • つまり、誰かがどこかでインスタンス作ってくれてる
  • その「誰か」は Spring
  • タイミングは「依存注入されるとき」

🛠 Beanの作成方法

JavaコードでBeanを作るには @Configuration クラス内で @Bean を使う:

@Configuration
public class AppConfig {

    @Bean
    public MyCustomThing customThing(MyDependency dep) {
        return new MyCustomThing(dep);
    }
}

💭 よくある疑問

❓ 引数が必要なクラスはどうするの?

ここで渡している MyDependency も、Beanとして登録されている必要がある

@Bean
public MyCustomThing customThing(MyDependency dep) {
    return new MyCustomThing(dep);
}

つまり、Springが管理しているインスタンスしか渡せない。

❓ Userみたいに動的に値が変わるクラスは?
無理。

User のようにリクエストごとに id, name が違うようなオブジェクトはBeanにできない。

→ リクエストごとに異なる値を持つもの=Beanにはしない

🧬 Beanの使い方

@Service
public class UserService {
    private final MyCustomThing myCustom;

    public UserService(MyCustomThing myCustom) {
        this.myCustom = myCustom;
    }
}

コンストラクタの引数に書くだけで、Springが自動でインスタンス化してくれる

この形が推奨。なぜなら:

  • DIのタイミングが明確

  • final が使える(テスト時に安心)

⚠️ フィールドに直接書く方法は非推奨

@Autowired
private MyCustomThing myCustom;

これはできるけど 非推奨。

  • どのタイミングでDIされるかわかりづらい

  • final が使えない

  • テストしづらい

🏷 ちなみに:@Service@Repository もBeanです
@Service, @Repository, @Component などは、暗黙的にBean登録されるアノテーション

📝 まとめ

  • Beanは共通・固定のインスタンス管理に向いている

  • リクエストごとに変わる値はBeanに向かない

  • コンストラクタで注入(DI)しよう

  • @Bean は明示的なDI設定が必要なときだけでOK

  • @Service などでの自動管理が基本

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?