2017-08-28 102 views
4

假设这个类图:如何在不更改代码的情况下将限制应用到Spring/hibernate企业应用程序中的所有业务点?

enter image description here

我有一个名为Organization许多对象有关联的那类。除了StoreHousePersonnel之外,还有许多对象,但是为了具有简单的类图,我没有将这些类放入图中(假定超过1000个类依赖于Organization类)。

现在,我想添加enabled字段到Organization类。这很简单,没有任何问题。但在此之后,我想阻止所有业务点和服务使用disabled组织。

例如假定此以下服务:

@Service 
public class PersonnelService { 
    @Autowired 
    private PersonnelRepository repository; 

    public long save(Personnel entity) { 
     return repository.save(entity); 
    } 
} 

如果我有以上应用程序中的代码,enabled字段添加到Organization后,我应该上述方法改变为这样:

@Service 
public class PersonnelService { 
    @Autowired 
    private PersonnelRepository repository; 

    public long save(Personnel entity) { 

     if(!entity.getOrganization().getEnabled()) { 
      throw Exception(); 
     } 

     return repository.save(entity); 
    } 
} 

而因为这个动作非常耗时,要换1000多班。 我想知道是否有办法在不更改业务点的情况下执行此操作(例如使用Aspect或类似方法),并检测修改是在对象上进行的,并且其类型为Organization的字段检查enabled值?

+0

定义'@ Where'上过滤的'enabled'属性的组织。这样残疾人组织就看不见了。 –

回答

0

我假设你使用弹簧数据Jpa或弹簧数据休息来实现更新。如果是的话可以做到这一点如下:

创建注释UpdateIfTrue

@Documented 
@Target(ElementType.TYPE) 
@Retention(RUNTIME) 
public @interface UpdateIfTrue { 
    String value(); 
} 

创建服务

@Service("updateIfTrueService") 
public class UpdateIfTrueService { 

    public boolean canUpdate(Object object){ 

     Class klass = object.getClass(); 
     UpdateIfTrue updateIfTrue = (UpdateIfTrue) klass.getAnnotation(UpdateIfTrue.class); 
     if (updateIfTrue != null){ 
      String propertyTree[] = updateIfTrue.value().split("."); 

      /*Traverse heirarchy now to get the value of the last one*/ 
      int i=0; 
      try{ 
       while(i<propertyTree.length){ 
        for (Field field : klass.getDeclaredFields()){ 
         if (field.getName().equalsIgnoreCase(propertyTree[i])){ 
          if (i < (propertyTree.length - 1)){ 
           i++; 
           klass = field.getClass(); 
           object = field.get(object); 
           break; 
          } 
          else if (i == (propertyTree.length - 1)){ 
           i++; 
           klass= field.getClass(); 
           object = field.get(object); 
           return (Boolean)object; 
          } 
         } 
        } 
       } 
      }catch(Exception e){ 
       e.printStackTrace(); 
      } 
     }else{ 
      return true; 
     } 
     return true; 
    } 
} 

注释要进行检查的实体。例如,用户有以下标注

@UpdateIfTrue("personnel.organization.enabled") 

现在在Repository做以下

@Override 
@PreAuthorize("@updateIfTrueService.canUpdate(#user)") 
User save(@Param("user")User user); 
相关问题