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


    案例1 隐式扫描不到Bean的定义

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    @RestController
    public class HelloWorldController {
    
        @RequestMapping(path = "/hiii",method = RequestMethod.GET)
        public String hi() {
            return "hi hellowrd";
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    @SpringBootApplication
    @RestController
    public class ApplicationContext {
    
        public static void main(String[] args) {
            SpringApplication.run(ApplicationContext.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    发现不在同一级的包路径,这个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 {
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    ComponentScan有一个属性是扫描对应的路径注解,

    	/**
    	 * Base packages to scan for annotated components.
    	 */
    	@AliasFor("value")
    	String[] basePackages() default {};
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ComponentScanAnnotationParser.parse的方法,declaringClass所在的包其实就是主方法的包,也就是com.qxlx
    在这里插入图片描述
    好了,我们找到问题所在了,加一行这个自定义路径就可以了。

    @ComponentScan("com.qxlx")
    
    • 1

    定义的Bean缺少隐式依赖

    @Service
    public class UserService {
    
        private String serviceName;
    
        public UserService(String serviceName) {
            this.serviceName = serviceName;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    一启动的时候,就发现异常了。

    Parameter 0 of constructor in com.qxlx.service.UserService required a bean of type 'java.lang.Integer' that could not be found.
    
    • 1
     @Bean
     public String serviceName() {
         return "qxlx";
     }
    
    • 1
    • 2
    • 3
    • 4

    添加如下bean就可以修复。启动正常。

  • 相关阅读:
    flink学习-容错机制
    Mysql索引
    Python 代码托管到码云平台,原来这么简单
    Spring-Cloud-Alibaba-SEATA源码解析(一)(客户端)
    强势借力Arbitrum,看代币ARC如何大放异彩
    在一张 24 GB 的消费级显卡上用 RLHF 微调 20B LLMs
    【学习笔记44】JavaScript的事件传播
    vscode windows mingw配置
    2023年合肥市青少年信息学科普日活动(初中组)
    C++程序员入门需要怎么学?(InsCode AI 创作助手)
  • 原文地址:https://blog.csdn.net/jia970426/article/details/134232895