6

Today, we found this pattern in our code:

class Foo {
    private List<String> errors;

    public void addError(String error) { ... }
    public List<String> getErrors();
}

While the code seems to work, this is a singleton Spring bean and it's injected in several independent places and the consumers of the bean assume that they each have their own list of errors. So this introduces subtle bugs.

The obvious solution is to educate developers to avoid this kind of error but I was wondering if there is a static or runtime code analysis tool which can find this kind of bug.

For example, a bean postprocessor could analyze the bean before it's returned and look for private fields that aren't @Autowired.

4

2 に答える 2

1

これにさらに頭脳(私たちと他の人々)を注いだ後、私たちはこのアプローチを思いつきました:

  1. BeanPostProcessorすべてのシングルトン Bean (つまり、Bean 定義のスコープが である場所) が実際の Bean タイプにSingletonカスタム アノテーションを持っていることを確認する をインストールします。@Stateless

    @Singleton他の場所でもこの機能が必要なため、再利用する代わりにカスタム アノテーションを選択しました。

    注釈が欠落している場合、ファクトリはエラーをスローします。

  2. 単体テストでは、ClassPathScanningCandidateComponentProviderカスタム アノテーションを使用せずにクラスパス上のすべてのクラスを検索します。その後、複雑で費用のかかるテストを実行して、Bean の状態が初期構成後 (つまり、オートワイヤリングが発生した後) に変更されないことを確認できます。

自動配線されたフィールドをコンストラクターに移動すると、2 番目のステップが少し簡単になる可能性がありますが、非常に多くの引数を取るメソッドは好きではありません。Java または IDE が Bean コードからビルダーを生成できるとよいでしょう。そうではないので、自動配線されたフィールドやセッターに固執します。

于 2013-08-26T13:02:45.483 に答える
0

アプリ構成をロードする JUnit テストを作成できます。これは、ここから ListableBeanFactory を組み合わせることができます:

Spring 構成ファイルで Bean をスキャンしてリストを動的に作成できますか?

ここで「isSingleton」をチェックしてください:

Spring Bean のプロトタイプ スコープを適用する方法

つまり、アプリ コンテキスト内のすべての Bean を一覧表示し、どれがシングルトンかを確認します。

これにより、すべてのシングルトン Bean を見つけることができます。

于 2013-07-26T14:14:16.217 に答える