软件: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/bS1GMhttp://t.csdn.cn/bS1GM
@Autowired注入方式是byType,如果只有一个实现类,会装配那个实现类。如果有两个实现类,会报错。
@Resource默认按照byName,找不到再byType
@Resource(name="实现类名")//也可以@Resource
@Qualifier 也是 byName。
@Qualifier("实现类名")文章来源:https://www.toymoban.com/news/detail-494878.html
@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);
}
}
服务实现类文章来源地址https://www.toymoban.com/news/detail-494878.html
@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;
}
}
到了这里,关于谷粒商城p45-自动装配-stream流-lambda表达式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!