java - 无法自动接线
问题描述
使用 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...";
}
}
堆栈跟踪
在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl) 的线程“restartedMain”java.lang.reflect.InvocationTargetException 中的异常.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) 原因:java.lang。 NullPointerException at com.example.demo.services.Maker.printName(Maker.java:15) at com.example.demo.DemoApplication.main(DemoApplication.java:17) ... 还有 5 个
解决方案
如果您使用new
该 bean 不会添加到的关键字创建任何 bean Spring Application Context
,这是@Autowire
静态 bean的一种方法
@SpringBootApplication
public class DemoApplication {
@Autowired
private static Maker maker;
@Autowired
private Maker tMaker;
@PostConstruct
public void init() {
DemoApplication.maker = tMaker;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
maker.printName();
}
}
或者您可以在创建时Autowire
使用被注入Constructor
的实例Maker
作为构造函数的参数DemoApplication
@Autowired
public DemoApplication(Maker maker) {
DemoApplication.maker = maker;
}
或者您可以@Autowired
在 setter 方法上使用,setter 方法在创建Maker
时的实例中调用DemoApplication
@Autowired
public void setMaker(Maker maker) {
DemoApplication.maker = maker
}
推荐阅读
- c# - 打开文件并在超时的情况下异步获取 FileStream
- python - 使用 os 遍历图像文件
- delphi - Delphi 10:关于 String[25] 将一些 char 值更改为“?”我能做些什么?
- javascript - 从单个组件访问多个 easy-peasy 商店
- python - 验证views.py
- python - 使用 aiosqlite 的 sqlite 列中的最后一个值
- java - 第一次尝试 Java 和 Gradle 进行 minecraftforge 开发;在 ScriptPluginFactory 和 FileHasher 中的 Gradle 中出现奇怪的错误
- python - 如何让 Discord 机器人给我想要的角色?
- dax - PowerBi 中两个计算列之间的 DateDiff 错误
- dataframe - 使用附加列将数据框从宽转换为长