gpt4 book ai didi

java - 无法 Autowiring

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:07:50 26 4
gpt4 key购买 nike

使用 Spring Initializer 创建一个简单的 Spring boot。我只在可用选项下选择 DevTools。

创建项目后,无需对其进行任何更改,即可正常运行程序。

现在,当我尝试在项目中进行一些 Autowiring 时,它根本不起作用。我不明白。一直在这里查看以前的所有问题,这些问题都有解决方案,但没有一个有效,而且我在我的案例中所做的事情并不复杂,如下所示。请告知我所缺少的。

@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...";
}
}

堆栈跟踪

Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) Caused by: java.lang.NullPointerException at com.example.demo.services.Maker.printName(Maker.java:15) at com.example.demo.DemoApplication.main(DemoApplication.java:17) ... 5 more

最佳答案

如果您使用 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 时作为参数注入(inject)构造函数已创建

@Autowired
public DemoApplication(Maker maker) {
DemoApplication.maker = maker;
}

或者您可以使用 @Autowired在 setter 方法上,使用 Maker 的实例调用 setter 方法什么时候DemoApplication已创建

@Autowired
public void setMaker(Maker maker) {
DemoApplication.maker = maker
}

关于java - 无法 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51909671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com