了解弹簧靴@Autowired
2022-09-04 07:46:23
我不明白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"); }
}
当我执行此代码时,我获取日志和 ,因此 spring 会创建此对象。但是当我从 in 调用 init 方法时,我得到一个 .除了使用注释来初始化我的对象之外,我还需要做更多的事情吗?init App
init Starter
Starter
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