• [Spring Boot] Use Component Scan to scan for Bean


    Component Scan is important concept when we want to create Bean. 

    Currently we know what, for the class, we want to create Bean from it, we need to add @Component.

    @Component
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public class ComponentPersonDAO {
    
        @Autowired
        ComponentJDBCConnection jdbcConnection;
    
        public ComponentJDBCConnection getJdbcConnection() {
            return jdbcConnection;
        }
    
        public void setJdbcConnection(ComponentJDBCConnection jdbcConnection) {
            this.jdbcConnection = jdbcConnection;
        }
    }

    Another important thing to know that How Spring Boot knows where to find those @Component, this is where @ComponentScan comes into play. by default, it assume search inside the same package. If inside same package cannot find the Bean, then it will report error.

    For example, our main function is inside package called:  

    com.example.in28minutes
    package com.example.in28minutes;
    
    import componentScan.ComponentPersonDAO;
    ...
    
    @SpringBootApplication
    public class In28minutesComponentScanApplication {
    
        private static Logger LOGGER = LoggerFactory.getLogger(In28minutesComponentScanApplication.class);
    
        public static void main(String[] args) {
            // Application Context
            ...
    
        }
    }

    But where we import ComponentPersonDAO.java from another package: 

    componentScan

    In this case, the code won't work, it reports that cannot find ComponentPersonDAO bean.

    To fix the problem, we can add @ComponentSan("componentScan").

    package com.example.in28minutes;
    
    import componentScan.ComponentPersonDAO;
    
    @SpringBootApplication
    @ComponentScan("componentScan")
    public class In28minutesComponentScanApplication {
    
        ...
    
        }
    }

     It tells the Spring to scan for component inside "componentScan" package.

  • 相关阅读:
    【3.5】类和实例属性的查找顺序--mro查找
    【3.4】类变量和实例变量
    【3.3】isinstance和type的区别
    【3.2】抽象基类(abc模块)
    【3.1】鸭子类型和多态
    学习笔记 | 浅谈虚拟函数(Virtual Function)
    学习笔记 | Udacity CarND Term 1: Computer Vision and Deep Learning
    命令行 | File Compression in Linux
    Python: if else in a list comprehension
    Topic | Hyperparameter Optimization for Neural Networks
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10678851.html
Copyright © 2020-2023  润新知