SpringBoot项目将数据源变成Json文件(Jackson2RepositoryPopulatorFactoryBean实现)

2023-11-06

一。项目情景

有时在我们项目当中需要存储一些固定值时,会使用一些配置文件来存储,例如最常见的.json文件。它可以用来存储相应的属性以及属性值,当你需要的时候进行提取,甚至还可以基于这个.json文件写一些条件查询的语句来获得自己需要的值。

本篇博客的示例项目就是将角色权限控制的信息存入到.json文件中,再使用Jackson2RepositoryPopulatorFactoryBean更换.json文件为数据源,在根据需求条件查询获取某个特定用户角色的权限控制关系。

二。项目搭建

说明:

该项目角色有三种,分别为studentteacher以及admin,我们可以控制对应角色的ui权限。简单来说就是控制各个角色能在页面上的操作,是只能看(READ),还是能看也能改(READ_WRITE)
1)在pom.xml文件中引入springframework data依赖:

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-keyvalue</artifactId>
        </dependency>

2)角色权限控制rule_definitions.json内容如下:

[
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 1,
    "roleId": "*",
    "resourceId": "studentNo",
    "resourceContext": "student-ui/update-form",
    "action": "READ"
  },
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 2,
    "roleId": "teacher",
    "resourceId": "studentNo",
    "resourceContext": "student-ui/update-form",
    "action": "READ_WRITE"
  },
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 3,
    "roleId": "admin",
    "resourceId": "studentNo",
    "resourceContext": "student-ui/update-form",
    "action": "READ_WRITE"
  },
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 4,
    "roleId": "*",
    "resourceId": "studentName",
    "resourceContext": "student-ui/update-form",
    "action": "READ"
  },
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 5,
    "roleId": "*",
    "resourceId": "studentAge",
    "resourceContext": "student-ui/update-form",
    "action": "READ"
  },
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 6,
    "roleId": "*",
    "resourceId": "studentSex",
    "resourceContext": "student-ui/update-form",
    "action": "READ"
  },
  {
    "_class": "com.example.jsondemo.dto.RuleDefinition",
    "ruleId": 7,
    "roleId": "*",
    "resourceId": "studentPhone",
    "resourceContext": "student-ui/update-form",
    "action": "READ"
  }
]

各个属性解析:

  • _class:实体类所在的包位置,类似于连接数据库时对应实体的包位置。
  • ruleId:计数标志
  • roleId:用户角色Id,就是项目角色。“*”是通配符,在本项目中,代表匹配student、teacher以及admin三种项目角色。
  • resourceId:资源Id,相当于前端UI界面的一个button的名称。
  • resourceContext:资源上下文,相当于某个UI界面的名称。
  • action:操作名称,代表该角色Id下有哪种操作权限。

3)RuleDefinition实体代码如下:

package com.example.jsondemo.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;

import java.io.Serializable;

/**
 * @author Keson
 * @version 1.0
 * @description: TODO 权限控制实体
 * @date 2021/9/15 11:12
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RuleDefinition implements Serializable {

    @Id
    private Integer ruleId;
    private String roleId;
    private String resourceId;
    private String resourceContext;
    private String action;
}

4)config配置类代码如下(更换配置源为上述自定义的json文件):

package com.example.jsondemo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean;

/**
 * @author Keson
 * @version 1.0
 * @description: TODO 更换数据源配置
 * @date 2021/9/15 11:46
 */
@Configuration
public class RepositoryConfig {

    @Value("${rules.datasource}")
    private String ruleDefinitionFilePath;

    @Bean
    public Jackson2RepositoryPopulatorFactoryBean getRepository(){
        Jackson2RepositoryPopulatorFactoryBean factoryBean = new Jackson2RepositoryPopulatorFactoryBean();
        factoryBean.setResources( new Resource [] { new ClassPathResource(ruleDefinitionFilePath) } );
        return factoryBean;
    }
}

5)repository层代码如下:

package com.example.jsondemo.repository;

import com.example.jsondemo.dto.RuleDefinition;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RuleDefinitionRepository extends CrudRepository<RuleDefinition, Integer> {

    List<RuleDefinition> findByResourceContextEqualsAndRoleIdEqualsOrResourceContextEqualsAndRoleIdIn
            (String wildcardResourceContext, String roleId, String resourceContext, List<String> roleIds);
}

6)service层代码如下:

package com.example.jsondemo.service;

import com.example.jsondemo.dto.RuleDefinition;

import java.util.List;

/**
 * @author Keson
 * @version 1.0
 * @description: TODO 权限控制service
 * @date 2021/9/15 11:31
 */
public interface RuleDefinitionService {

    List<RuleDefinition> getRules (String wildcardResourceContext, String roleId, String resourceContext, List<String> roleIds);
}

package com.example.jsondemo.service.impl;

import com.example.jsondemo.dto.RuleDefinition;
import com.example.jsondemo.repository.RuleDefinitionRepository;
import com.example.jsondemo.service.RuleDefinitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Keson
 * @version 1.0
 * @description: TODO 权限控制service的实现
 * @date 2021/9/15 11:32
 */
@Service
public class RuleDefinitionServiceImpl implements RuleDefinitionService {

    @Autowired
    private RuleDefinitionRepository ruleDefinitionRepository;

    @Override
    public List<RuleDefinition> getRules(String wildcardResourceContext, String roleId, String resourceContext, List<String> roleIds) {
        return ruleDefinitionRepository.findByResourceContextEqualsAndRoleIdEqualsOrResourceContextEqualsAndRoleIdIn
                (wildcardResourceContext, roleId, resourceContext, roleIds);
    }
}

7)控制层代码如下:

package com.example.jsondemo.api;

import com.example.jsondemo.dto.RuleDefinition;
import com.example.jsondemo.service.RuleDefinitionService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Keson
 * @version 1.0  权限控制API
 * @description: TODO
 * @date 2021/9/15 11:34
 */
@RestController
@RequestMapping("/v1")
public class RuleDefinitionApi {

    @Autowired
    private RuleDefinitionService RuleDefinitionService;

    @GetMapping("/getRules")
    List<RuleDefinition> getRules(@RequestParam("resourceContext")String resourceContext,
                                  @RequestParam("roleId")String roleId,
                                  @RequestParam("roleIds")List<String> roleIds){
        return RuleDefinitionService.getRules(resourceContext, roleId, resourceContext , roleIds);
    }
}

8)配置文件application.yml内容如下:

server:
  port: 8080 #端口号
  servlet:
    context-path: /${spring.application.name}

spring:
  application:
    name: json-demo #服务名称

# 配置json数据源所在位置
rules:
  datasource: "rules/rule_definitions.json"

9)启动类代码如下:

package com.example.jsondemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.map.repository.config.EnableMapRepositories;

@EnableMapRepositories
@SpringBootApplication
public class JsonDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(JsonDemoApplication.class, args);
    }

}

注意:
@EnableMapRepositories注解一定不要忘记添加,负责项目会启动失败!!!

10)项目创建完成后杰哥如下:
在这里插入图片描述

三。测试

1)使用postman访问接口,先使用角色Id为student的进行传入:
在这里插入图片描述
发现student角色对studentNo只有READ(读)权限。

2)更换为teacher再访问:
在这里插入图片描述
发现teacher角色对studentNo有READ_WRITE(读写)权限。

3)至此,我们使用json文件为数据源实现了角色权限控制的功能。

四。项目下载

本博客示例项目已经上传至gitee,需要的下伙伴可以自行下载:
https://gitee.com/hair_gel_king/json-demo/tree/master

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot项目将数据源变成Json文件(Jackson2RepositoryPopulatorFactoryBean实现) 的相关文章

随机推荐

  • mysql 字符串分割函数substring_index用法

    实现和python split 函数一样的功能 mysql用函数substring index 用法 substring index str 分隔符 第n个分隔符之前的所有字符or倒数第n个分隔符之后的所有字符 例子 select subs
  • Qt4_深入信号和槽

    信号和槽 信号和槽是Qt 编程的一个重要部分 这个机制可以在对象之间彼此并不了解的情况下将它们的行为联系起来 在前几个例程中 我们已经连接了信号和槽 声明了控件自己的信号和槽 并实现了槽函数 发送了信号 现在来更深入了解这个机制 槽和普通的
  • 【Java】【字符串】IP地址与整数的相互转换

    package itheima2 import java util Scanner public class Main public static void main String args Scanner scanner new Scan
  • MFC程序的诞生与死亡

    MFC程序的诞生与死亡 程序的诞生 Application object产生 内存于是获得配置 初值亦设立了 Afx WinMain执行AfxWinInit 后者又调用AfxInitThread 把消息队列尽量加大到96 AfxWinMai
  • django 国际化

    一 开启国际化 1 setting中默认语言改为 LANGUAGE CODE es es 2 添加中间件 django middleware locale LocaleMiddleware MIDDLEWARE CLASSES django
  • 「数字货币监管」听证会重磅来袭,无形之笼悄然降临?

    美国的国会老爷们要认真讨论数字货币的监管问题了 一个全方位的数字货币监管框架正在成型 作者 唐晗 编辑 秦晋 出品 碳链价值 ID cc value 美国国会对数字货币上瘾了 7月30日 美国参议院银行 住房和城市事务委员会将于华盛顿时间上
  • 配置wsl外网访问(实操步骤)

    介绍 wsl存在一个ip1 window存在一个ip2 ip1无法ping通与ip2处于同一网段下的ip 此种情况下 涉及到网络通信相关的开发就比较困难 本文介绍配置wsl外网的访问 操作步骤 获取wsl的ip 管理员身份在powershe
  • Jenkins安装部署与自动化部署网站实战

    1 CICD与Jenkins概述 互联网软件的开发和发布 已经形成了一套标准流程 假如把开发工作流程分为以下几个阶段 编码 构建 集成 测试 交付 部署 在上图中看到 持续集成 Continuous Integration 持续交付 Con
  • 数据结构-1

    1 2 线性结构树状结构网状结构 表 数 图 数据 数值型 非数值型 1 2 3数据类型和抽象数据类型 1 3抽象数据类型 概念小结 线性表 如果在独立函数实现的 c 文件中需要包含 stdlib h 头文件 而主函数也需要包含 stdli
  • 服务器部署Java项目详述

    前言 记录一下自己从0到1部署Java前后端项目到服务器上的过程 过程梗概 首先要先买一个服务器 一般用CentOS7 然后大概步骤是再配置一下所买的服务器环境 再安装下对应我们的Java项目所需要的一些应用程序即可 其中 Nginx是用来
  • 如何部署LVS + keepalived 负载均衡高可用集群

    目录 一 LVS架构 概念 L4和L7负载均衡的区别 keepalive故障自动切换 抢占与非抢占 二 keepalived管理LVS负载均衡器 LVS集中节点的健康检查 三 部署LVS keeplived 高可用集群 第一步 关闭防火墙和
  • Scala中 常用容器类的函数/方法

    1 foreach 迭代遍历集合中的每个元素 对每个元素进行处理 但是没有返回值 常用于打印结果数据 val ls List 1 3 5 7 9 ls foreach println 打印每个元素 ls foreach println 打印
  • kzalloc 函数详解

    用kzalloc申请内存的时候 效果等同于先是用 kmalloc 申请空间 然后用 memset 来初始化 所有申请的元素都被初始化为 0 kzalloc allocate memory The memory is set to zero
  • wpf

    Windows Presentation Foundation WPF 是微软新一代图形系统 运行在 NET Framework 3 0架构下 为用户界面 2D 3D 图形 文档和媒体提供了统一的描述和操作方法 基于DirectX 9 10
  • DP和HDMI区别

    转自 https www toutiao com i6877677362054595080 在目前市面上显示器接口中 VGA和DVI已经逐渐退出了历史舞台 Type C还算是小众 而DP DisplayPort 与HDMI则成为了主流产品的
  • 普通人在chatGPT的3个赚钱机会

    短短的2个多月内 到处都在讨论ChatGPT 不管你有没有参与其中 以GPT为代表的AI工具已经进化到一个很恐怖的程度了 比如说最近爆火的AutoGPT 能按照一个指令自动干活了 好想试一下 让AutoGPT自动帮我分析福利彩票 ChatG
  • 实现el-form一行中多个el-form-item

    el form item默认一个占一行 利用el row和el col实现一行中多个 注意 el col span 12 中的12是一个占据的列数 默认一列总共24列 通过调整这个数字 可以调整不同列的宽度 如果只使用el col 不在外面
  • c++23中的新功能之一介绍

    一 c 23的目标和延革 c 的标准发展速度在经过c 11的近乎可以称革新的变化之后 开始步入了快车道 有的人在网上说 c 11后的c 语言和c 11以前的c 语言不是一个语言 这有点夸张了 但不可否认 其内容确实变化非常大 很多人可能都没
  • 异步处理机制 多线程

    在处理程序执行流程时 一定要切记 android的处理机制是异步处理 多线程的它并不会因为一个线程处于阻塞状态时其他的线程就不往下执行了 看看代码是不是一个线程的 如果是一个线程的 线面就阻塞了 转载于 https www cnblogs
  • SpringBoot项目将数据源变成Json文件(Jackson2RepositoryPopulatorFactoryBean实现)

    一 项目情景 有时在我们项目当中需要存储一些固定值时 会使用一些配置文件来存储 例如最常见的 json文件 它可以用来存储相应的属性以及属性值 当你需要的时候进行提取 甚至还可以基于这个 json文件写一些条件查询的语句来获得自己需要的值