スプリングブーツのアノテーション@Autowired
が正しく機能するか分かりません。ここでは簡単な例です:スプリングブートについて@Autowired
@SpringBootApplication
public class App {
@Autowired
public Starter starter;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public App() {
System.out.println("init App");
//starter.init();
}
}
- 私はこのコードを実行すると
@Repository
public class Starter {
public Starter() {System.out.println("init Starter");}
public void init() { System.out.println("call init"); }
}
、私はログinit App
とinit Starter
を取得するので、春には、このオブジェクトを作成します。しかし、からApp
にinitメソッドを呼び出すと、私はNullPointerException
となります。オブジェクトを初期化するために、注釈@Autowired
を使用してさらに必要なものはありますか?
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [{package}.App$$EnhancerBySpringCGLIB$$87a7ccf]: Constructor threw exception; nested exception is java.lang.NullPointerException
をあなたのBeanのスコープに応じて、春理由ブートアプリケーションはパッケージスキャンを使用するようにあらかじめ設定されていますが、春は使用したいBeanのインスタンスを作成します。しかし、作成されたという理由だけで、必ずしも注入されたわけではありません。 – christopher