通过接口名,动态获取不同Bean对象

文章展示了在JavaSpring框架中,如何在Controller层通过ApplicationContextGetBeanHelper工具类获取Service层的Bean并进行方法调用。InterfaceService接口被用于服务调用,而JudgeNetTypeServiceImpl是一个具体的实现类,它实现了InterfaceService并注入了UserIntoDao。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

controller 层

//应用层,获取对象

InterfaceService interfaceService = (InterfaceService)ApplicationContextGetBeanHelper.getBean(interfaceName);

Object responseObject =interfaceService.invoke(reqParams);

获取对象方法

/**

 * Created by yangxine on 2021/5/13 9:58

 * 根据beanName获取不同Bean

 */

@Component

public class ApplicationContextGetBeanHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;

    }

    public static Object getBean(String className) throws BeansException,IllegalArgumentException {

        if(className==null || className.length()<=0) {

            throw new IllegalArgumentException("className为空");

        }

        String beanName = null;

        if(className.length() > 1) {

            beanName = className.substring(0, 1).toLowerCase() + className.substring(1);

        } else {

            beanName = className.toLowerCase();

        }

        return applicationContext != null ? applicationContext.getBean(beanName) : null;

    }

}

示例: 接口实现类

@Service("judgeNetType")

@Slf4j

public class JudgeNetTypeServiceImpl implements InterfaceService{

    @Autowired

    UserIntoDao userIntoDao;

    @Override

    public Object invoke(Map<String, String> reqParams) {

        

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值