@SpringBootApplication注解上指定扫描路径
时间: 2023-12-26 07:15:28 浏览: 49
@SpringBootApplication注解默认会扫描启动类所在包及其子包下的所有组件,包括@Controller、@Service、@Repository、@Component等注解的类。如果需要指定其他扫描路径,可以在@SpringBootApplication注解上使用@ComponentScan注解,例如:
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.controller", "com.example.service"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
上面的代码指定了扫描com.example.controller和com.example.service包下的组件。
相关问题
@SpringBootApplication 注解
@SpringBootApplication是一个组合注解,用于标注Spring Boot的主配置类。它包含了以下三个注解:
1. @SpringBootConfiguration:标注在某个类上,表示这是一个Spring Boot的配置类。该注解本身也是@Configuration的衍生注解,用于定义配置类。
2. @EnableAutoConfiguration:启用自动配置功能。Spring Boot会根据项目的依赖和配置,自动配置Spring应用程序上下文。它会根据类路径下的jar包和类上的注解来判断需要自动配置哪些功能。
3. @ComponentScan:指定Spring Boot应用程序的组件扫描的基础包。它会自动扫描并注册带有@Component、@Controller、@Service等注解的Bean。
综合来说,@SpringBootApplication的作用是将这三个注解组合在一起,方便快速启动一个Spring Boot应用程序,并进行自动配置和组件扫描。<em>1</em><em>2</em><em>3</em>
#### 引用[.reference_title]
- *1* *2* [@SpringBootApplication注解详解](https://blog.csdn.net/killerofjava/article/details/104375433)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
- *3* [@SpringBootApplication注解](https://blog.csdn.net/u010675669/article/details/109010552)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
[ .reference_list ]
@SpringBootApplication注解中@ConmentScan注解的作用
`@ComponentScan` 注解是 `Spring Framework` 中的一个注解,它的作用是扫描指定包及其子包下的所有类,将含有 `@Component` 及其派生注解的类注册为 `Spring` 容器中的 `Bean`。
`@SpringBootApplication` 是一个组合注解,包括了 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan` 三个注解。其中 `@ComponentScan` 默认扫描启动类所在包及其子包下的所有类,因此不需要再次指定扫描包的路径。但有时我们需要指定特定的扫描路径,那么就可以使用 `@ComponentScan` 注解进行配置。
例如:
```java
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.service", "com.example.controller"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
上面的代码中,我们指定了 `@ComponentScan` 注解扫描的路径为 `com.example.service` 和 `com.example.controller` 包及其子包下的所有类。这样所有含有 `@Component` 及其派生注解的类都会被注册为 `Spring` 容器中的 `Bean`。