私はSpringブートを使ってRESTサービスを開発しました。 RESTコントローラの1つでは、フィールドベースの依存性注入があり、これはコンストラクタベースの依存性注入に変更するのが好きです。依存関係注入の設定は、次のようになります。Springブートコンストラクタベースの依存性注入が機能しない
@RestController
public class ParameterDateController {
private ParameterDateController() {
}
private ParameterDate parameterDate;
private ParameterDateController(ParameterDate parameterDate) {
this.parameterDate = parameterDate;
}
@Autowired
private ParameterDateService parameterDateService;
// here are the metods of the endpoints
}
この設定ではすべて正常に動作します。私はベースのコンストラクタにParameterDateService
を変更するliktだろうと私はこれを試してみました:
@RestController
public class ParameterDateController {
private ParameterDateController() {
}
private ParameterDate parameterDate;
private ParameterDateController(ParameterDate parameterDate) {
this.parameterDate = parameterDate;
}
private ParameterDateService parameterDateService;
private ParameterDateController(ParameterDateService parameterDateService) {
this.parameterDateService = parameterDateService;
}
// here are the metods of the endpoints
}
をコンストラクタベースの依存性の注入に変更した後、私はNullPointerException
を取得し、私はこのparameterDateService.postParameterDate(parameterDate);
ような依存関係を注入しようとします。フィールドベースの依存性注入としてセットアップしたときと同じ方法で注入します。これはno NullPointerException
です。 ParameterDate
のコンストラクタベースの依存関係注入は、期待通りに機能します。
私は間違っていますか?
2番目のコンストラクタにAutowiredを追加する必要があります。または最初のものを削除します。あなたはまた、それを公開する必要があります:あなたは反射なしでは呼び出すことができないコンストラクタのポイントは何ですか?あなたがそれに満足しているなら、フィールド注入もいいです。 –