Java 了解 Spring Boot @Autowired
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38476486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding Spring Boot @Autowired
提问by
I don't understand how spring boot's annotation @Autowired
correctly works. Here is a simple example:
我不明白 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"); }
}
When I execute this code, I get the logs init App
and init Starter
, so spring creates this objects. But when I call the init method from Starter
in App
, I get a NullPointerException
. Is there more I need to do other than using the annotation @Autowired
to init my object?
当我执行这段代码时,我得到了日志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$a7ccf]: Constructor threw exception; nested exception is java.lang.NullPointerException
采纳答案by Jesper
When you call the init
method from the constructor of class App
, Spring has not yet autowired the dependencies into the App
object. If you want to call this method after Spring has finished creating and autowiring the App
object, then add a method with a @PostConstruct
annotation to do this, for example:
当您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();
}
}