完整报错如下:
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'testHelloController': Unsatisfied dependency expressed through field 'testHelloService'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'com.jun.service.test.TestHelloService' available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
原因分析:
因为是初学SpringBoot,只是想先让项目跑起来看看效果如果,费尽半天时间终于把项目结构搭建完整,一启动,就报这样的错,原因人家已经说得很清晰了,也就是在启动的时候找不到TestHelloService这个对象模板进行注入,又看了看service层已经打好注解@Service的,灵机一动,是不是SpringBoot启动的时候没有扫描得到Service层去,后面一看资料,果然如此,在SpringBoot的启动类Application中直接打一个注解@ComponentScan即可解决此问题:
如下:
报错前的代码:
package com.jun.web.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
解决报错后的代码:
package com.jun.web.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
**@ComponentScan(basePackages = {"com.jun.core.*","com.jun.service.*","com.jun.web.*"})**
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}