spring怎么开启包扫描
时间: 2024-05-20 20:19:35 浏览: 9
在 Spring 中开启包扫描可以通过在配置文件中配置 `<context:component-scan>` 标签来实现。具体步骤如下:
1. 在 Spring 配置文件中加入命名空间声明:
```xml
xmlns:context="http://www.springframework.org/schema/context"
```
2. 配置 `<context:component-scan>` 标签,指定需要扫描的包路径,例如:
```xml
<context:component-scan base-package="com.example.controller" />
```
上述配置将扫描 `com.example.controller` 包及其子包下所有带有 `@Controller`、`@Service`、`@Repository`、`@Component` 注解的类,并将其注册为 Spring 的 Bean。
3. 如果要开启自动装配,则需要在配置文件中加入以下配置:
```xml
<context:annotation-config />
```
这个配置会启用 Spring 对注解的支持,使得标注了 `@Autowired`、`@Value` 等注解的属性能够被成功注入。
总结一下,开启包扫描需要以下三个步骤:
1. 命名空间声明:
```xml
xmlns:context="http://www.springframework.org/schema/context"
```
2. 配置 `<context:component-scan>` 标签:
```xml
<context:component-scan base-package="com.example.controller" />
```
3. 开启注解支持:
```xml
<context:annotation-config />
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)