目录
方法一:利用 Spring ApplicationContext获取
方法二:SpringContextUtils工具类 上下文获取
方法一:利用 Spring ApplicationContext获取
1. 接口及实现类
/**
* @author sp
* @since 2019/10/24 10:38
*/
public interface SendMsgInter {
/**
* 发送 消息接口
*/
void sendMsg(String msg);
}
/**
* @author sp
* @since 2019/10/24 10:39
*/
@Service
public class AlipayHealthMsgImpl implements SendMsgInter {
private static final Logger logger = LoggerFactory.getLogger(AlipayHealthMsgImpl.class);
@Override
public void sendMsg(String msg) {
logger.info("支付宝生活号消息发送!" + msg);
}
}
/**
* @author sp
* @since 2019/10/24 10:39
*/
@Service
public class WechatMsgImpl implements SendMsgInter {
private static final Logger logger = LoggerFactory.getLogger(WechatMsgImpl.class);
@Override
public void sendMsg(String msg) {
logger.info("微信消息发送!" + msg);
}
}
2. 动态获取实现类
/**
* @author sp
* @since 2019/10/24 10:42
*/
@Service
public class SendMsgImplManage {
@Autowired
private ApplicationContext applicationContext;
public SendMsgInter getMsgInstance(String msgTypeCode){
switch (msgTypeCode){
case "1001":
return applicationContext.getBean(WechatMsgImpl.class);
case "1002":
return applicationContext.getBean(AlipayHealthMsgImpl.class);
default:
return null;
}
}
}
3. 测试用例
/**
* @author sp
* @since 2019/10/24 10:45
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
//@WebAppConfigurationpublic
p