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

  • Post author:
  • Post category:其他


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) {

}



版权声明:本文为ImSanJin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。