我是Spring的新手,过去几天我一直在学习它.现在我想用它做点什么.在我看来,春季靴子一切都发生了变化.
没有applicationContext文件,我应该使用@Bean.好.在教程中代码正在运行,对我来说它失败了.我错过了什么?
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
控制器:
@RestController
public class GreetingController {
private final Test test;
@Autowired
public GreetingController(Test test){
this.test = test;
}
@RequestMapping("/greeting")
public String greeting(@RequestParam(value = "name",defaultValue = "World") String name) {
return "greeting" + test.getTest();
}
}
class Test {
public String getTest() {
return "tetst";
}
}
错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hello.Test] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListablebeanfactory.raiseNoSuchBeanDefinitionException(DefaultListablebeanfactory.java:1301)
at org.springframework.beans.factory.support.DefaultListablebeanfactory.doResolveDependency(DefaultListablebeanfactory.java:1047)
at org.springframework.beans.factory.support.DefaultListablebeanfactory.resolveDependency(DefaultListablebeanfactory.java:942)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 18 more
我假设必须定义bean …但是在教程中没有bean的defenicion ..或者我没有看到它.
最佳答案
测试类不被识别为Spring组件.因此,您无法将其注入GreetingController中.要在该控制器中注入Test对象,请使用类似@Component注释(或使用一些其他注释指示您的类可以自动扫描)注释Test类.
原文链接:https://www.f2er.com/spring/431739.html