动态获取 实现类 反射

本文介绍了三种在Spring环境下动态获取实现类的方法,包括利用ApplicationContext获取、使用SpringContextUtils工具类以及通过类名反射获取并调用接口方法。详细阐述了每种方法的实现步骤,并给出了具体示例,特别强调了通过反射获取实现类时需要注意的初始化问题。
摘要由CSDN通过智能技术生成

目录

 

方法一:利用 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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值