Spring Boot集成mp根据实体类获取对应的Service 和mapper

首先实现spring容器 应用上下文

ApplicationContextAware

然后通过

applicationContext.getBeanNamesForType 去获取对应的容器

完整代码如下

@Component
public class ServiceUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ServiceUtils.applicationContext =applicationContext;
    }

    public static <T,S extends IService<T>> S getService(Class<T> clazz){
        String[] beanNames = applicationContext.getBeanNamesForType(ResolvableType.forClassWithGenerics(IService.class, clazz));
        return beanNames.length != 0 ? (S) applicationContext.getBean(beanNames[0]) : null;
    }

    public static <T,M extends BaseMapper<T>> M getMapper(Class<T> clazz){
        String[] mapperNames =  applicationContext.getBeanNamesForType(ResolvableType.forClassWithGenerics(BaseMapper.class, clazz));
        return mapperNames.length != 0 ? (M) applicationContext.getBean(mapperNames[0]) : null;
    }

}
请登录后发表评论