软件:idea、postman、virtual box
服务:gulimall-product
请求路径:http://localhost:10000/product/category/list/tree
启动:启动idea product模块,启动vm,启动docker mysql
controller代码
自动装配CategoryService对象
调用对象中的listWithTree()
自动装配相关,为什么用resource 不用 autowired:参考下面文章
http://t.csdn.cn/bS1GM http://t.csdn.cn/bS1GM
http://t.csdn.cn/bS1GM
 
@Autowired注入方式是byType,如果只有一个实现类,会装配那个实现类。如果有两个实现类,会报错。
@Resource默认按照byName,找不到再byType
@Resource(name="实现类名")//也可以@Resource
@Qualifier 也是 byName。
@Qualifier("实现类名")
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;
    /**
     * 查出所有分类以及子分类,以树形结构组装
     */
    @RequestMapping("/list/tree")
    //@RequiresPermissions("product:category:list")
    public R list(){
        List<CategoryEntity> entities = categoryService.listWithTree();
        return R.ok().put("data",entities);
    }
}服务实现类
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }
    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> entities = categoryDao.selectList(null);
        //组装成树
            //查找一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(menu -> menu.setChildren(getChildrens(menu,entities)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return level1Menus;
    }
    //递归查找菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity>all){
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .peek(menu -> menu.setChildren(getChildrens(menu, all)))
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
        return children;
    }
}


















