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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:21:57  来源:igfitidea点击:

Understanding Spring Boot @Autowired

javaspringspring-boot

提问by

I don't understand how spring boot's annotation @Autowiredcorrectly 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 Appand init Starter, so spring creates this objects. But when I call the init method from Starterin App, I get a NullPointerException. Is there more I need to do other than using the annotation @Autowiredto init my object?

当我执行这段代码时,我得到了日志init Appinit Starter,所以 spring 创建了这个对象。但是当我从Starterin调用 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 initmethod from the constructor of class App, Spring has not yet autowired the dependencies into the Appobject. If you want to call this method after Spring has finished creating and autowiring the Appobject, then add a method with a @PostConstructannotation 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();
    }
}