【发布时间】:2016-11-23 09:48:06
【问题描述】:
我不明白 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 创建了这个对象。但是当我在App 中从Starter 调用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 的范围,因为 Spring Boot 应用程序被预先配置为使用包扫描,所以 spring 将创建你想要使用的 bean 的实例。但是,仅仅因为它已经被创建,并不一定意味着它已经被注入。
标签: java spring spring-boot