spring aop组件

以下文章将显示在我参与的一个项目中,我们如何使用Spring的AOP来介绍一些与安全性相关的功能。 这样的概念是,为了使用户能够看到某些UI组件,他需要具有一定级别的安全特权。 如果不满足该要求,则不会显示UIComponent。 让我们看一下项目结构:

然后还有aopApplicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><aop:aspectj-autoproxy /><context:annotation-config /><context:component-scan base-package="pl.grzejszczak.marcin.aop"><context:exclude-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/></context:component-scan><bean class="pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor" factory-method="aspectOf"/> </beans>

现在,让我们看一下Spring应用程序上下文中最有趣的几行。 首先,我们拥有所有必需的模式-我认为不需要对此进行更深入的解释。 然后我们有:

<aop:aspectj-autoproxy/>

启用@AspectJ支持。 接下来是

<context:annotation-config />
<context:component-scan base-package="pl.grzejszczak.marcin.aop"><context:exclude-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>

首先,我们通过注释打开Spring配置。 然后,我们故意排除了由Spring本身将其初始化为Bean的方面。 为什么? 因为…

<bean class="pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor" factory-method="aspectOf"/>

我们希望自己创建方面,并提供factory-method =” aspectOf”。 这样,我们的方面将包含在我们的bean的自动装配过程中-因此,所有带有@Autowired注释的字段都将注入bean。 现在让我们继续执行代码:

UserServiceImpl.java

package pl.grzejszczak.marcin.aop.service;import org.springframework.stereotype.Service;import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.user.UserHolder;@Service
public class UserServiceImpl implements UserService {private UserHolder userHolder;@Overridepublic UserHolder getCurrentUser() {return userHolder;}@Overridepublic void setCurrentUser(UserHolder userHolder) {this.userHolder = userHolder;}@Overridepublic Role getUserRole() {if (userHolder == null) {return null;}return userHolder.getUserRole();}
}

UserServiceImpl类正在模仿一种服务,该服务将从数据库或当前应用程序上下文中获取当前用户信息。

UserHolder.java

package pl.grzejszczak.marcin.aop.user;import pl.grzejszczak.marcin.aop.type.Role;public class UserHolder {private Role userRole;public UserHolder(Role userRole) {this.userRole = userRole;}public Role getUserRole() {return userRole;}public void setUserRole(Role userRole) {this.userRole = userRole;}
}

这是一个简单的持有人类,其中包含有关当前用户角色的信息。

角色.java

package pl.grzejszczak.marcin.aop.type;public enum Role {ADMIN("ADM"), WRITER("WRT"), GUEST("GST");private String name;private Role(String name) {this.name = name;}public static Role getRoleByName(String name) {for (Role role : Role.values()) {if (role.name.equals(name)) {return role;}}throw new IllegalArgumentException("No such role exists [" + name + "]");}public String getName() {return this.name;}@Overridepublic String toString() {return name;}
}

角色是一个枚举,它为管理员作家来宾定义了一个角色。

UIComponent.java

package pl.grzejszczak.marcin.aop.ui;public abstract class UIComponent {protected String componentName;protected String getComponentName() {return componentName;}}

一些UI组件的具体实现的抽象。

SomeComponentForAdminAndGuest.java

package pl.grzejszczak.marcin.aop.ui;import pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation;
import pl.grzejszczak.marcin.aop.type.Role;@SecurityAnnotation(allowedRole = { Role.ADMIN, Role.GUEST })
public class SomeComponentForAdminAndGuest extends UIComponent {public SomeComponentForAdminAndGuest() {this.componentName = "SomeComponentForAdmin";}public static UIComponent getComponent() {return new SomeComponentForAdminAndGuest();}
}

此组件是UI组件扩展的示例,只有具有AdminGuest角色的用户才能看到。

SecurityAnnotation.java

package pl.grzejszczak.marcin.aop.annotation;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;import pl.grzejszczak.marcin.aop.type.Role;@Retention(RetentionPolicy.RUNTIME)
public @interface SecurityAnnotation {Role[] allowedRole();
}

定义可以创建此组件的角色的注释。

UIFactoryImpl.java

package pl.grzejszczak.marcin.aop.ui;import org.apache.commons.lang.NullArgumentException;
import org.springframework.stereotype.Component;@Component
public class UIFactoryImpl implements UIFactory {@Overridepublic UIComponent createComponent(Class<? extends UIComponent> componentClass) throws Exception {if (componentClass == null) {throw new NullArgumentException("Provide class for the component");}return (UIComponent) Class.forName(componentClass.getName()).newInstance();}
}

给定扩展UIComponent的对象类的工厂类将返回给定UIComponent的新实例。

SecurityInterceptor.java

package pl.grzejszczak.marcin.aop.interceptor;import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.List;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;import pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation;
import pl.grzejszczak.marcin.aop.service.UserService;
import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.ui.UIComponent;@Aspect
public class SecurityInterceptor {private static final Logger LOGGER = LoggerFactory.getLogger(SecurityInterceptor.class);public SecurityInterceptor() {LOGGER.debug("Security Interceptor created");}@Autowiredprivate UserService userService;@Pointcut("execution(pl.grzejszczak.marcin.aop.ui.UIComponent pl.grzejszczak.marcin.aop.ui.UIFactory.createComponent(..))")private void getComponent(ProceedingJoinPoint thisJoinPoint) {}@Around("getComponent(thisJoinPoint)")public UIComponent checkSecurity(ProceedingJoinPoint thisJoinPoint) throws Throwable {LOGGER.info("Intercepting creation of a component");Object[] arguments = thisJoinPoint.getArgs();if (arguments.length == 0) {return null;}Annotation annotation = checkTheAnnotation(arguments);boolean securityAnnotationPresent = (annotation != null);if (securityAnnotationPresent) {boolean userHasRole = verifyRole(annotation);if (!userHasRole) {LOGGER.info("Current user doesn't have permission to have this component created");return null;}}LOGGER.info("Current user has required permissions for creating a component");return (UIComponent) thisJoinPoint.proceed();}/*** Basing on the method's argument check if the class is annotataed with* {@link SecurityAnnotation}* * @param arguments* @return*/private Annotation checkTheAnnotation(Object[] arguments) {Object concreteClass = arguments[0];LOGGER.info("Argument's class - [{}]", new Object[] { arguments });AnnotatedElement annotatedElement = (AnnotatedElement) concreteClass;Annotation annotation = annotatedElement.getAnnotation(SecurityAnnotation.class);LOGGER.info("Annotation present - [{}]", new Object[] { annotation });return annotation;}/*** The function verifies if the current user has sufficient privilages to* have the component built* * @param annotation* @return*/private boolean verifyRole(Annotation annotation) {LOGGER.info("Security annotation is present so checking if the user can use it");SecurityAnnotation annotationRule = (SecurityAnnotation) annotation;List<Role> requiredRolesList = Arrays.asList(annotationRule.allowedRole());Role userRole = userService.getUserRole();return requiredRolesList.contains(userRole);}
}

这是在执行函数createComponent的切入点处定义的方面
UIFactory接口。 在“ 周围” 建议中,存在一种逻辑,该逻辑首先检查将什么样的参数传递给方法createComponent(例如SomeComponentForAdminAndGuest.class)。 接下来,将检查此类是否使用SecurityAnnotation进行注释,如果是,它将检查创建组件所需的角色类型。 然后,它检查当前用户(从UserService到UserHolder的Roles)是否具有呈现组件所需的角色。 如果是这样的话
调用thisJoinPoint.proceed(),实际上返回扩展UIComponent的类的对象。 现在让我们对其进行测试–这是SpringJUnit4ClassRunner

AopTest.java

package pl.grzejszczak.marcin.aop;import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import pl.grzejszczak.marcin.aop.service.UserService;
import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForAdmin;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForAdminAndGuest;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForGuest;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForWriter;
import pl.grzejszczak.marcin.aop.ui.UIFactory;
import pl.grzejszczak.marcin.aop.user.UserHolder;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:aopApplicationContext.xml" })
public class AopTest {@Autowiredprivate UIFactory uiFactory;@Autowiredprivate UserService userService;@Testpublic void adminTest() throws Exception {userService.setCurrentUser(new UserHolder(Role.ADMIN));Assert.assertNotNull(uiFactory.createComponent(SomeComponentForAdmin.class));Assert.assertNotNull(uiFactory.createComponent(SomeComponentForAdminAndGuest.class));Assert.assertNull(uiFactory.createComponent(SomeComponentForGuest.class));Assert.assertNull(uiFactory.createComponent(SomeComponentForWriter.class));}
}

和日志:

pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:26 Security Interceptor created
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForAdmin]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[ADM])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:70 Current user has required permissions for creating a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForAdminAndGuest]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[ADM, GST])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:70 Current user has required permissions for creating a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForGuest]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[GST])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:66 Current user doesn't have permission to have this component created
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForWriter]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[WRT])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:66 Current user doesn't have permission to have this component created

单元测试显示,对于给定的Admin角色,仅创建了前两个组件,而对于其他两个,则返回null(由于用户没有适当的权限)。 这就是在我们的项目中,我们如何使用Spring的AOP创建一个简单的框架,该框架将检查用户是否可以创建给定的组件。 由于对各个方面进行了编程,因此不必记住编写任何与安全性相关的代码,因为它将为他完成。

参考: 安全性中的Spring AOP –通过我们的JCG合作伙伴 Marcin Grzejszczak(位于Blog上)上的代码瘾君子博客来控制UI组件的创建 。

翻译自: https://www.javacodegeeks.com/2013/04/spring-aop-in-security-controlling-creation-of-ui-components-via-aspects.html

spring aop组件

spring aop组件_安全性中的Spring AOP –通过方面控制UI组件的创建相关推荐

  1. 安全性中的Spring AOP –通过方面控制UI组件的创建

    以下文章将显示在我参与的一个项目中,我们如何使用Spring的AOP来介绍一些与安全性相关的功能. 这样的概念是为了使用户能够看到一些UI组件,他需要具有一定级别的安全特权. 如果不满足该要求,则不会 ...

  2. 【鸿蒙 HarmonyOS】Ability 中使用纯代码绘制布局及 UI 组件

    文章目录 一.Ability 与 Slice 简介 二.Ability 中使用纯代码绘制布局及 UI 组件 三.Ability 中使用纯代码绘制布局及 UI 组件代码示例 四.GitHub 地址 一. ...

  3. spring ioc原理_这70 道Spring高频面试题,你不好奇吗?

    对于面试来说,Spring是必问知识.如何了解和掌握核心内容呢? 这里总结打磨了 70 道 Spring 相关面试题,有的很基础,有的很细节,大家可以评估一下自己掌握的情况. Spring 重点要掌握 ...

  4. spring.jpa配置_使用JPA和Spring 3.1进行事务配置

    spring.jpa配置 1.概述 本教程将讨论配置Spring Transactions ,使用@Transactional批注和常见陷阱的正确方法 . 有关核心持久性配置的更深入讨论,请查看Spr ...

  5. Spring实战 | 第二部分 Web中的Spring(第五章 构建Spring Web应用程序)

    第五章 构建Spring Web应用程序 映射请求到Spring控制器 透明地绑定表单参数 校验表单提交 一.Spring MVC起步 1.跟踪spring MVC的请求 在请求离开浏览器时,会带有用 ...

  6. Spring boot(6)---在Eclipse中搭建Spring boot 项目

    Spring boot入门:在Eclipse中搭建Spring boot 项目 Eclipse中的STS插件 打开Eclipse-Help-Eclipse Marketplace-popular 下载 ...

  7. api 微信小程序组件库colorui_微信小程序常用的几个UI组件库

    1.WeUI WeUI 是一套同微信原生视觉体验一致的基础样式库,由微信官方设计团队为微信 Web 开发量身设计,可以令用户的使用感知更加统一.包含button.cell.dialog. progre ...

  8. qt ui界面无法移动控件_使用qt 键盘上的方向键只能控制ui界面上的按钮选择,不能实现我设定的功能...

    已结贴√ 问题点数:20 回复次数:2 使用qt 键盘上的方向键只能控制ui界面上的按钮选择,不能实现我设定的功能 我做的是一个贪吃蛇游戏,现在我想实现的功能是:按下键盘上的上下左右箭头的方向按键时, ...

  9. java aop面试_我想知道Spring在面试中应该怎么介绍,以及如何介绍他的aop?

    Spring是一个开源框架,它由Rod Johnson创建.它是为了解决企业应用开发的复杂性而创建的.Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情.然而,Spring的用途 ...

最新文章

  1. windows下使用Hibernate连接Mycat例子
  2. 【Python】青少年蓝桥杯_每日一题_11.03_按要求输出两个正整数之间的数
  3. Android-FixBug热修复框架的使用及源码分析(不发版修复bug)
  4. 生物岛实验室闵明玮课题组诚聘副研究员/博士后/科研助理/实习生
  5. Connect Three
  6. Java学习笔记50:JSONObject与JSONArray的使用
  7. Django开发中常用的命令总结
  8. 【正则表达式】正则表达式匹配SQL中的函数名
  9. 吴恩达机器学习之单变量线性回归理论部分
  10. 为什么Python是数据科学领域最受欢迎的语言之一?
  11. 用jsonp 解决跨域问题
  12. c语言的编译器还真是不好理解...
  13. Atitit USRqc62204 证书管理器标准化规范
  14. Keil 使用教程(详解)
  15. 达梦数据库/DM7迁移之导出sql脚本
  16. eemd优缺点_改进EEMD算法在心电信号去噪中的应用
  17. EfficientNet论文解读
  18. Shell编码规范手册(shellcheck错误汇总)
  19. 售票计算机 制票机的使用方法,铁路客运计算机售票具体操作.pdf
  20. 程序开发团队---团队精神篇

热门文章

  1. MySQL last_insert_id()函数
  2. Eclipse中看不到jsp的页面效果
  3. JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)
  4. auto.js小案例
  5. 2020蓝桥杯省赛---java---A---4(七段码)
  6. springboot创建项目 编写dao serviece 和controller 持久层用mybatis
  7. 保定有国家承认的计算机学校吗,河北省122所大学名单,不在名单内的都是国家不承认的野鸡学校...
  8. 做一个完整的Java Web项目需要掌握的技能
  9. tomcat(supplement)HttpConnector.initialize() 和 start() 方法 以及 StandardContext.start()方法的分析
  10. DFS——深度优先搜索基础