以下是一个使用 Spring Boot 实现的简单 IoC(控制反转)示例。这个示例展示了如何通过 Spring 容器管理对象的创建和依赖关系,从而降低代码耦合度。
项目结构
src/main/java/com/example/iocdemo
├── IOCDemoApplication.java (主程序)
├── UserService.java (业务接口)
├── UserServiceImpl.java (业务实现类)
└── OrderService.java (依赖注入的类)
1. 创建 Spring Boot 项目
首先,确保你已经安装了 Java 和 Maven。然后创建一个 Spring Boot 项目,可以通过 Spring Initializr 生成,或者手动创建。
Maven 依赖
在 pom.xml
中添加 Spring Boot 依赖:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
2. 编写代码
IOCDemoApplication.java
package com.example.iocdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class IOCDemoApplication {
public static void main(String[] args) {
// 启动 Spring 容器
ApplicationContext context = SpringApplication.run(IOCDemoApplication.class, args);
// 从容器中获取 UserService Bean
UserService userService = context.getBean(UserService.class);
userService.sayHello(); // 调用方法
}
}
UserService.java
package com.example.iocdemo;
public interface UserService {
void sayHello();
}
UserServiceImpl.java
package com.example.iocdemo;
import org.springframework.stereotype.Service;
// 使用 @Service 注解将 UserServiceImpl 注册为 Spring Bean
@Service
public class UserServiceImpl implements UserService {
@Override
public void sayHello() {
System.out.println("Hello from UserService!");
}
}
OrderService.java
package com.example.iocdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final UserService userService;
// 通过构造函数注入 UserService
@Autowired
public OrderService(UserService userService) {
this.userService = userService;
}
public void processOrder() {
System.out.println("Processing order...");
userService.sayHello(); // 调用 UserService 的方法
}
}
3. 运行结果
运行 IOCDemoApplication
后,输出如下:
Hello from UserService!
4. 关键点解析
控制反转(IoC):
UserServiceImpl
和OrderService
都通过@Service
注解注册为 Spring Bean。- Spring 容器负责创建和管理这些对象,而不是由程序员手动实例化。
OrderService
通过构造函数注入(@Autowired
)依赖UserService
,实现了依赖关系的解耦。
依赖注入(DI):
OrderService
的构造函数中使用了@Autowired
注解,Spring 会自动将UserService
的实现类注入到OrderService
中。- 如果需要更换
UserService
的实现类,只需修改配置文件或注解,无需修改OrderService
的代码。
松耦合:
OrderService
只依赖于UserService
接口,而不是具体的实现类,降低了代码的耦合度。- 如果需要扩展功能,只需新增一个实现类并注册为 Spring Bean,无需修改现有代码。
5. 扩展
- XML 配置:如果不使用注解,可以通过 XML 文件配置 Bean。例如:
<bean id="userService" class="com.example.iocdemo.UserServiceImpl"/> <bean id="orderService" class="com.example.iocdemo.OrderService"> <constructor-arg ref="userService"/> </bean>
- AOP 集成:可以结合 AOP 实现日志记录、事务管理等功能。
- 动态代理:Spring 默认使用动态代理实现 AOP,如果目标类没有实现接口,会使用 CGLIB 生成子类代理。
通过这个简单的示例,你可以快速理解 Spring 中的 IoC 和 DI 概念,并将其应用到实际项目中。