【发布时间】:2019-01-25 08:08:50
【问题描述】:
使用 Spring Initializer 创建一个简单的 Spring boot。我只在可用选项下选择 DevTools。
创建项目后,无需对其进行任何更改,即可正常运行程序。
现在,当我尝试在项目中进行一些自动装配时,它根本不起作用。我不明白。一直在这里查看以前的问题,这些问题有解决方案,但没有一个有效,而且我在我的情况下所做的事情并不复杂,如下所示。请告知我所缺少的。
@SpringBootApplication
public class DemoApplication {
// @Autowired
// private static Maker maker; // Stopped using this cos I wanted to check if the autowiring is not working in this class only or anywhere. Turns out it is anywhere.
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
Maker maker = new Maker();
maker.printName(); // Fails cos of ServiceHelper Autowiring
}
}
@Service
public class Maker {
@Autowired
private ServiceHelper serviceHelper;
public void printName(){
System.out.println("This is from the method body itself.");
System.out.println("Auto wiring works cos I got this -> " + serviceHelper.help());
}
}
@Component
public class ServiceHelper {
public String help(){
return "...FROM HELPER...";
}
}
堆栈跟踪
线程“restartedMain”中的异常 java.lang.reflect.InvocationTargetException 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:497) 在 org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) 引起:java.lang.NullPointerException at com.example.demo.services.Maker.printName(Maker.java:15) 在 com.example.demo.DemoApplication.main(DemoApplication.java:17) ... 5 更多
【问题讨论】:
-
您不能自动装配静态字段。
-
@DarrenForsythe 我已经注释掉了静态字段。
-
@kang 检查我的答案以解决在静态字段中注入依赖项的工作。
标签: java spring-boot