spring 依赖注入示例
时间: 2023-09-13 09:07:49 浏览: 53
好的,下面是一个简单的 Spring 依赖注入示例:
假设我们有一个接口 `UserService` 和一个实现类 `UserServiceImpl`,如下所示:
```java
public interface UserService {
void addUser();
}
@Component
public class UserServiceImpl implements UserService {
public void addUser() {
System.out.println("Add user...");
}
}
```
其中,`@Component` 注解用于标识该类为 Spring 的一个组件,Spring 会自动将其注册到容器中。
然后,我们在另一个类中使用 `@Autowired` 注解来注入 `UserService`:
```java
@Component
public class UserController {
@Autowired
private UserService userService;
public void addUser() {
userService.addUser();
}
}
```
在上面的示例中,我们使用 `@Autowired` 注解将 `UserService` 注入到了 `UserController` 类中,并在 `addUser()` 方法中调用了 `userService` 的 `addUser()` 方法。
最后,我们需要在 Spring 的配置文件中声明 `UserController` 和 `UserServiceImpl`:
```xml
<beans>
<context:component-scan base-package="com.example" />
</beans>
```
其中,`context:component-scan` 标签用于扫描指定包下的所有组件,并将其注册到 Spring 容器中。
这样,在运行时,Spring 会自动创建 `UserController` 和 `UserServiceImpl` 的实例,并将 `UserServiceImpl` 注入到 `UserController` 中,从而实现依赖注入。