LoginSignup
10
10

More than 5 years have passed since last update.

staticフィールドを@Autowiredの対象にしたい

Posted at

とりわけユーティリティクラスの設計に際して、staticフィールドを@Autowiredの対象にしたい場面があります。この場合は対象のstaticフィールドのsetterを非staticメソッドとして定義し、そのsetterに対して@Autowiredを付与してやればよいようです。以下がその例となります。

public class SampleClass {

    private static StaticField staticField;

    @Autowired
    public void setStaticField(StaticField staticField) {
        SampleClass.staticField = staticField;
    }

}

ただし見るからにバッドノウハウなので、上記のようなことを頻繁に繰り返さねばならないようであれば、当該クラスをシングルトンにするなど、設計の見直しが必要になりそうです。もっともそう簡単に設計を見直したりできないのがシステム開発の現実なのですが(´・ω・`)

10
10
4

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
10
10