gpt4 book ai didi

java - 为什么Spring应用程序在使用@autowire时崩溃

转载 作者:行者123 更新时间:2023-12-01 17:42:41 26 4
gpt4 key购买 nike

我使用的是最新版本的IntelliJIDEA CE版(11.0.4)。有件事我在任何地方都找不到,它阻碍了我进一步改进 Java/Spring。

Controller :

import com.example.demo.classes.SaveToFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {
@Autowired protected SaveToFile saveToFile;
//@Autowired SaveToDb saveToDb;

@RequestMapping("/start")
public String whatever(@RequestParam(value="name", defaultValue="World") String name) {
saveToFile.save(name);
return "something";
//return new SaveToFile(name);
}
}

类别: 导入 com.example.demo.interfaces.ISave;

public class SaveToFile implements ISave {

private String filename = "Vlad";

@Override
public void save(String name) {
System.out.println("Saving " + name + " to file.");
}

public String getFilename(){
return filename;
}
}

类接口(interface):

public interface ISave {
void save(String name);
}

没什么花哨的,只是为了掌握 Spring 和 Java。

在我的 Controller 内,当我尝试使用

@Autowired protected SaveToFile saveToFile;

我收到阻止应用程序启动的错误。这是错误:

Execution failed for task ':DemoApplication.main()'.

Process 'command '/Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

如果我注释掉它,我可以用“new”实例化我的类,但这不是重点。

我尝试在“项目结构”菜单选项中更改 SDK。但无济于事。也许值得指出的是,我也在 Kotlin 中从事的类似项目完全没有问题。我尝试模仿“Kotlin”设置,但一无所获。

有人知道这里发生了什么吗?

最佳答案

您应该使用 @Component 注释 SaveToFile 类,或者在任何配置中创建该类型的 Bean(带注释的 @Bean) @Autowired 工作的类。

关于java - 为什么Spring应用程序在使用@autowire时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106774/

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