10

上記のタイトルのように、@ Autowiredアノテーションを直接使用してapplicationContextを注入することと、シングルトンSpringBeanにApplicationContextAwareインターフェイスを実装することの長所と短所について混乱しています。

どの場合にどちらが好きですか、そしてその理由は何ですか?ありがとう。

4

5 に答える 5

12

Actually, both are bad. Both of them tie your application to the Spring framework, thus inverting the whole inversion-of-control concept. In an ideal world, your application should not be aware of being managed by an ApplicationContext at all.

Once you have chosen to violate this principle, it doesn't really matter how you do it. ApplicationContextAware is the legacy version that has been around at least since Version 2.0. @Autowired is a newer mechanism but they work in pretty much the same way. I'd probably go with ApplicationContextAware, because it semantically makes clear what it is about.

于 2012-03-12T07:22:21.553 に答える
2

@Sean Patrick Floyd が言うように、ApplicationContext の必要性は多くの場合、設計が悪いことが原因です。しかし、他に選択肢がない場合もあります。そのような場合、他のすべてのプロパティを注入する方法であるため、@Autowired の使用を好みます。では、MyRepository の注入に @Autowired を使用する場合、ApplicationContext やその他の Spring Bean に使用できないのはなぜですか?

Spring インターフェースは、BeanNameAware などのアノテーションではできないことに対してのみ使用します。

于 2012-03-12T12:06:18.230 に答える
2

シングルトンでプロトタイプを取得する必要がある場合は、メソッド インジェクションを使用できます。基本的に、必要なオブジェクトを返す抽象メソッドを作成すると、Spring はそのメソッドを呼び出すたびにプロトタイプを返します。spring config で「lookup-method」を定義します。ここにいくつかのリンクがあります: http://docs.spring.io/spring/docs/1.2.9/reference/beans.html#beans-factory-method-injection http://java.dzone.com/articles/method-射出ばね

于 2013-09-10T19:12:48.530 に答える
0

Spring クラスを拡張していないため、アプリケーションは常にフレームワークから分離されています。ほとんどの場合、をそのまま注入するのApplicationContextではなく、 で定義された Bean を注入する必要がありApplicationContextます。

最良のケースは、特定の要件がない限り、常に最小限に固執することであり、これは春には非常に簡単です。

だからどちらか、

  1. で Bean とscanそれらに注釈を付けてからapplication context、 を使用@Autowireしてそれらを結び付けます。

  2. application contextBean の便宜 (古い xml スタイルの構成) を配線するために使用します。@Autowireこのアプローチでも使用できます 。

Bean のライフサイクルを制御したい場合は、API を読み取ってカスタマイズできますが、ほとんどの場合、これらの一般的な設定で十分です。

下記は用例です。

  1. @Autowired アノテーション付きの Spring 自動配線 Bean
  2. Spring 自動配線 Beans XML スタイル
  3. Spring IC コンテナー API ドキュメント
于 2012-03-12T08:16:53.820 に答える