@Autowired自动注入实现策略模式

项目场景:

支付时,需要根据用户选择的不同支付方式进行相应处理


实现方式

定义一个通用的支付接口及相应方法,并根据不同的支付方式编写相应的实现类,同时利用spring的自动注入机制(@Autowired),在bean注入时将所有实现类注入,并在执行时判断用户所选择的支付方式,然后进行相应的处理。

实现代码

策略接口

public interface IPaymentStrategy {
	boolean accept(String paymentMethod);
	void invokePay(Param param);
}

实现类

@Service("ALiPayment")
public class ALiPayment implements IPaymentStrategy {
	@Override
	public boolean accept(String paymentMethod) {
		return "ALiPayment".equals(paymentMethod);
	}
	
	@Override
	public void invokePay(Param param) {
		System.out.println("使用支付宝进行支付");
	}
}

@Service("WXPayment")
public class ALiPayment implements IPaymentStrategy {
	@Override
	public boolean accept(String paymentMethod) {
		return "WXPayment".equals(paymentMethod);
	}
	
	@Override
	public void invokePay() {
		System.out.println("使用微信进行支付");
	}
}

入口类1

@Component
public class userPayService {
	@Autowired
    private List<IPaymentStrategy> paymentStrategies;
    
    public void pay(String paymentMethod){
    	IPaymentStrategy paymentStrategy = Optional.ofNullable(paymentStrategies).orElseGet(null)
                .stream().filter(p -> p.accept(paymentMethod))
                .findFirst().orElse(null);
        if(paymentStrategy == null){
            throw new RuntimeException("can not find paymentStrategy ");
        }
        paymentStrategy.invokePay();
	}
}

入口类2

@Component
public class userPayService {
	@Autowired
    private Map<String, IPaymentStrategy> paymentStrategies;
    
    public void pay(String paymentMethod){
    	IPaymentStrategy paymentStrategy = paymentStrategies.get(paymentMethod);
        if(paymentStrategy == null){
            throw new RuntimeException("can not find paymentStrategy ");
        }
        paymentStrategy.invokePay();
	}
}

BY THE WAY:

也可使用自定义注解+反射的方式实现策略模式

@AutowiredSpring框架中的一种依赖注入(Dependency Injection,DI)注解,它简化了bean之间的依赖关系管理,使得代码更易于理解和维护。当你在方法或字段上使用 @Autowired 标注,Spring容器会自动查找并设置相应的bean实例。然而,在某些情况下,你可能不使用 @Autowired 注入: 1. **手动创建或配置**: 有时候,你可能需要对依赖进行特殊的处理或配置,比如使用工厂模式创建对象,或者需要在运行时动态确定依赖关系。 2. **单元测试**: 在编写单元测试时,你通常不需要完整的依赖注入上下文,可以使用构造函数注入或Mock对象来模拟依赖,以便更好地控制测试流程。 3. **控制初始化顺序**: 如果你需要明确控制bean的初始化顺序,使用 @Autowired 可能无法满足这个需求,此时可以手动调用 setter 方法或者使用 @PostConstruct 注解的方法。 4. **性能考虑**: 如果在一个高并发环境中,频繁的依赖查找可能会增加应用启动和运行时的开销,这时手动管理依赖可能会更高效。 5. **避免无限循环依赖**: 如果存在环状依赖,使用 @Autowired 可能导致无限循环,这时需要手动解除循环或者采用其他策略。 6. **学习和理解**: 对于初学者来说,了解如何手动管理依赖有助于深入理解设计模式和Spring框架的工作原理。 如果你决定不使用 @Autowired,一定要确保有足够的理由,并且代码能够正确地处理依赖关系和初始化。相关问题如下: 1. Spring框架还有哪些依赖注入方式? 2. 如何在不使用@Autowired的情况下手动设置bean? 3. 在什么情况下,手动构造对象比使用@Autowired更合适?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值