案例1 隐式扫描不到Bean的定义
@RestController
public class HelloWorldController {@RequestMapping(path = "/hiii",method = RequestMethod.GET)public String hi() {return "hi hellowrd";}}
@SpringBootApplication
@RestController
public class ApplicationContext {public static void main(String[] args) {SpringApplication.run(ApplicationContext.class,args);}
}
发现不在同一级的包路径,这个URL访问失败,那么是什么原因呢
其实就在这个main所对应的类的注解上,SpringBootApplication有一个对应的注解那就是ComponentScan
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}
), @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
ComponentScan有一个属性是扫描对应的路径注解,
/*** Base packages to scan for annotated components.*/@AliasFor("value")String[] basePackages() default {};
ComponentScanAnnotationParser.parse的方法,declaringClass所在的包其实就是主方法的包,也就是com.qxlx
好了,我们找到问题所在了,加一行这个自定义路径就可以了。
@ComponentScan("com.qxlx")
定义的Bean缺少隐式依赖
@Service
public class UserService {private String serviceName;public UserService(String serviceName) {this.serviceName = serviceName;}
}
一启动的时候,就发现异常了。
Parameter 0 of constructor in com.qxlx.service.UserService required a bean of type 'java.lang.Integer' that could not be found.
@Beanpublic String serviceName() {return "qxlx";}
添加如下bean就可以修复。启动正常。