1. 控制反转 (IoC)
工厂模式: 在工厂模式中,对象的创建是由工厂类负责的,客户端通过调用工厂方法来获取对象实例。
`getBean`: `getBean` 是 Spring 框架中的一个方法,用于从 Spring 容器中获取 Bean 实例。Spring 容器管理了对象的生命周期和依赖关系,实现了控制反转 (IoC)。
2. 依赖管理
工厂模式: 工厂模式需要手动管理对象的依赖关系,通常在工厂方法中进行依赖注入。
`getBean`: Spring 容器自动管理对象的依赖关系,通过配置文件或注解方式声明依赖,容器会自动注入所需的依赖。
3. 灵活性
工厂模式: 工厂模式提供了较高的灵活性,可以通过不同的工厂方法创建不同类型的对象。
`getBean`: `getBean` 方法提供了多种重载形式,可以根据不同的参数获取不同类型的 Bean,灵活性也很高。
4. 配置复杂度
工厂模式: 需要编写工厂类和工厂方法,配置相对复杂。
`getBean`: 只需要在 Spring 配置文件或注解中声明 Bean,配置相对简单。
5. 代码侵入性
工厂模式: 工厂模式需要在客户端代码中显式调用工厂方法,增加了代码的耦合度。
`getBean`: 使用 `getBean` 方法时,客户端代码只需要调用 `getBean`,减少了代码的耦合度,符合 IoC 原则。
6. 性能
工厂模式: 创建对象的性能取决于工厂方法的实现。
`getBean`: Spring 容器在初始化时会预加载和缓存 Bean,多次调用 `getBean` 获取同一个 Bean 时性能较好。
案例比较
场景描述
假设我们有一个简单的应用,需要根据不同的条件创建不同类型的 UserService 实例。我们将分别使用工厂模式和 getBean 来实现这个需求。
工厂模式代码
1. 定义接口和实现类
// UserService 接口
public interface UserService {
void doSomething();
}
// 具体实现类1
public class UserServiceImpl1 implements UserService {
@Override
public void doSomething() {
System.out.println("Doing something with UserServiceImpl1");
}
}
// 具体实现类2
public class UserServiceImpl2 implements UserService {
@Override
public void doSomething() {
System.out.println("Doing something with UserServiceImpl2");
}
}
2. 创建工厂类
public class UserServiceFactory {
public static UserService getUserService(String type) {
if ("type1".equals(type)) {
return new UserServiceImpl1();
} else if ("type2".equals(type)) {
return new UserServiceImpl2();
} else {
throw new IllegalArgumentException("Invalid type");
}
}
}
3. 客户端代码
public class Client {
public static void main(String[] args) {
String type = "type1"; // 或者 "type2"
UserService userService = UserServiceFactory.getUserService(type);
userService.doSomething();
}
}
getBean 示例
1. 定义接口和实现类
// UserService 接口
public interface UserService {
void doSomething();
}
// 具体实现类1
@Component("userServiceImpl1")
public class UserServiceImpl1 implements UserService {
@Override
public void doSomething() {
System.out.println("Doing something with UserServiceImpl1");
}
}
// 具体实现类2
@Component("userServiceImpl2")
public class UserServiceImpl2 implements UserService {
@Override
public void doSomething() {
System.out.println("Doing something with UserServiceImpl2");
}
}
2. 配置 Spring 容器,在 application.yml 中配置 Spring 容器,确保 Spring 能够扫描到这些 Bean。
# application.yml
spring:
application:
name: jeecg-boot-erp
profiles:
active: dev
3. 客户端代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Client {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext("com.example");
String type = "userServiceImpl1"; // 或者 "userServiceImpl2"
UserService userService = context.getBean(type, UserService.class);
userService.doSomething();
}
}
结论
工厂模式适用于需要高度自定义对象创建逻辑的场景,但配置和维护成本较高。
getBean 则更适合于依赖管理和对象生命周期管理,特别是在使用 Spring 框架的项目中,getBean提供了更简洁、灵活和低侵入性的解决方案。
如果你在使用 Spring 框架,推荐使用 `getBean` 和其他 Spring 提供的 IoC 功能,以简化开发和维护工作。