Java spring启动依赖注入
我是春天的新手,最近几天我一直在学习。现在我想用它做点什么。在我看来,有了spring boot,一切都变了。 没有applicationContext文件,我应该使用@Bean。好啊在教程中,代码是有效的,但对我来说它失败了。我错过了什么Java spring启动依赖注入,java,spring,spring-mvc,spring-boot,Java,Spring,Spring Mvc,Spring Boot,我是春天的新手,最近几天我一直在学习。现在我想用它做点什么。在我看来,有了spring boot,一切都变了。 没有applicationContext文件,我应该使用@Bean。好啊在教程中,代码是有效的,但对我来说它失败了。我错过了什么 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Applicati
@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的防御。。或者我没有看到它。
Test
类未被识别为Spring组件。因此,您不能将其注入到您的问候控制器中。为了在该控制器中注入Test
对象,请使用like@Component
注释对Test
类进行注释(或使用一些其他注释,指示可以自动扫描您的类)。忽略了完整错误。您需要在测试中使用@Component
什么包是应用程序
和欢迎控制器
@SpringBootApplication
扫描控制器和组件,但它们必须在同一个包或更低级别的包中。