根据不同业务类型动态切换实现类(applicationContext.getBeansOfType实现)
本文以获取不同银行账户余额为例,具体实现如下:
整体结构:
IBankService.java
/** * 银行接口 */ public interface IBankService { /** * 查询账户余额 */ void getBalance(); }
AbcService.java
import org.springframework.stereotype.Service; /** 农业银行实现类 * @description: * @author: jack * @time: 2022/5/9 15:31 */ @Service("abcService") public class AbcService implements IBankService { @Override public void getBalance() { System.out.println("您的农行余额为1000元"); } }
CcbService.java
import org.springframework.stereotype.Service; /** 建设银行实现类 * @description: * @author: jack * @time: 2022/5/9 15:34 */ @Service("ccbService") public class CcbService implements IBankService { @Override public void getBalance() { System.out.println("您的建行余额为2000元"); } }
BankFactory.java
import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * @description: * @author: jack * @time: 2022/5/9 15:24 */ @Service("bankFactory") public class BankFactory implements InitializingBean, ApplicationContextAware { // 实现接口的实现类集合 private Map<String,IBankService> bankMap = new HashMap<>(); // 声明上下文 private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { // 根据上下文获取实现接口的实现类 Map<String,IBankService> mapBeans = applicationContext.getBeansOfType(IBankService.class); // 遍历集合并赋值 for (String beanName : mapBeans.keySet()) { IBankService bean = mapBeans.get(beanName); bankMap.put(beanName, bean); } } public IBankService getBankService(String beanName) { return bankMap.get(beanName); } }
BankTestController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @description: * @author: jack * @time: 2022/5/9 15:36 */ @RestController public class BankTestController { @Autowired private BankFactory bankFactory; @RequestMapping("/getBalance") public void getBalance(@RequestParam("bankName")String bankName) { IBankService bankService = bankFactory.getBankService(bankName+"Service"); bankService.getBalance(); } }
测试调用:
http://localhost:8039/getBalance?bankName=abc
控制台打印:您的农行余额为1000元
http://localhost:8039/getBalance?bankName=ccb
控制台打印:您的建行余额为2000元