• 【源码解析】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就可以修复。启动正常。

  • 相关阅读:
    【Android】点击短信链接唤起APP的方案实践
    CET4汉译英part
    django-项目
    [树上倍增]Eezie and Pie 2022牛客多校第6场 B
    openGauss运维操作命令及其相关介绍
    深度学习笔记之优化算法(三)动量法的简单认识
    elasticsearch配置密码、docker数据迁移、IP白名单
    MySQL数据库
    linux学习实操计划0202-安装Melts
    如何使用 PHP 和 MySQL 创建分页
  • 原文地址:https://blog.csdn.net/jia970426/article/details/134232895