【源码解析】Spring Bean定义常见错误

编程入门 行业动态 更新时间:2024-10-22 20:40:32

【<a href=https://www.elefans.com/category/jswz/34/1770099.html style=源码解析】Spring Bean定义常见错误"/>

【源码解析】Spring Bean定义常见错误

案例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就可以修复。启动正常。

更多推荐

【源码解析】Spring Bean定义常见错误

本文发布于:2023-11-16 11:12:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619629.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:源码   定义   错误   常见   Bean

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!