[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.

posted @   Zhentiw  阅读(200)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-04-09 [Performance] Optimize Paint and Composite for the website
2017-04-09 [Angular] Implementing a ControlValueAccessor
点击右上角即可分享
微信分享提示