在Spring Boot中,@ComponentScan注解用于指定Spring框架扫描的包路径,从而初始化那些组件,比如@Component、@Service、@Repository和@Controller等。
如果你想要改变Spring Boot默认的组件扫描行为,可以使用@ComponentScan注解来指定不同的包路径。
以下是一个使用@ComponentScan的例子:
// 假设你的Spring Boot应用类位于com.example.demo包下,并且你想要Spring扫描com.example.service包下的组件
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.example.service") // 指定扫描的包路径
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}在上面的例子中,@ComponentScan注解指定了Spring应该扫描com.example.service包下的组件。如果你不使用basePackages属性,Spring将默认扫描@ComponentScan注解所在类的同级包及其子包中的组件。