权限管理代码与图解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/459148dc2d80fb224be85159105d1a08.png#pic_center)
@getter@setter
public class Permission extends BaseDomain{
private String name;
private String expression;
}
public abstract class PermissionUtil {
public static String buildExpression(Method m){
String className = m.getDeclaringClass().getName();
return className+":"+m.getName();
}
}
@Controller
@RequestMapping("permission")
public class PermissionController {
@Autowired
private IPermissionService permissionService;
@RequiredPermission("加载权限")
@RequestMapping("reload")
public ModelAndView reload() throws Exception{
permissionService.reload();
return null;
}
}
public interface IPermissionService {
void reload();
}
@Service
public class PermissionServiceImpl implements IPermissionService {
@Autowired
private PermissionMapper permissionMapper;
@Autowired
private ApplicationContext ctx;
public void reload() {
List<String> exprs = permissionMapper.selectAllExpression();
Collection<?> beans = ctx.getBeansWithAnnotation(Controller.class).values();
for (Object ctrl : beans) {
Method[] methods = ctrl.getClass().getDeclaredMethods();
for (Method m : methods) {
RequiredPermission anno = m.getAnnotation(RequiredPermission.class);
if (anno != null){
String exp = PermissionUtil.buildExpression(m);
if (!exprs.contains(exp)){
Permission p = new Permission();
p.setName(anno.value());
p.setExpression(exp);
permissionMapper.insert(p);
}
}
}
}
}
}
public interface PermissionMapper {
void insert(Permission entity);
List<String> selectAllExpression();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.PermissionMapper">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into permission(name,expression)
values (#{name},#{expression})
</insert>
<select id="selectAllExpression" resultType="string">
select expression from permission;
</select>
</mapper>