大佬教程收集整理的这篇文章主要介绍了了解Spring Boot @Autowired,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当您init
从class的构造函数调用该方法时App
,Spring尚未将依赖项自动关联到App
对象中。如果要在Spring完成App
对象的创建和自动装配之后调用此方法,请添加带有@postconstruct
注释的方法来执行此操作,例如:
@SpringBootApplication
public class App {
@autowired
public Starter starter;
public static voID main(String[] args) {
SpringApplication.run(App.class, args);
}
public App() {
System.out.println("constructor of App");
}
@postconstruct
public voID init() {
System.out.println("Calling starter.init");
starter.init();
}
}
我不了解Spring Boot的注释如何@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
,因此spring会创建此对象。但是当我从Starter
in
调用init方法时App
,我得到了一个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
以上是大佬教程为你收集整理的了解Spring Boot @Autowired全部内容,希望文章能够帮你解决了解Spring Boot @Autowired所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。