Java 如何在没有更改代码的情况下将限制应用到spring/hibernate企业应用程序中的所有业务点?
假设这个类图: 我有一个名为Java 如何在没有更改代码的情况下将限制应用到spring/hibernate企业应用程序中的所有业务点?,java,spring,hibernate,aop,business-logic,Java,Spring,Hibernate,Aop,Business Logic,假设这个类图: 我有一个名为Organization的类,许多对象都与之关联。除了仓库和人员,还有很多对象,但是为了有简单的类图,我没有把这些类放到图中(假设超过1000个类依赖于组织类) 现在,我想将enabled字段添加到Organization类中。它非常简单,没有任何问题。但在那之后,我想阻止所有业务点和服务使用禁用的组织 例如,假设以下服务: @Service public class PersonnelService { @Autowired private Per
Organization
的类,许多对象都与之关联。除了仓库
和人员
,还有很多对象,但是为了有简单的类图,我没有把这些类放到图中(假设超过1000个类依赖于组织
类)
现在,我想将enabled
字段添加到Organization
类中。它非常简单,没有任何问题。但在那之后,我想阻止所有业务点和服务使用禁用的
组织
例如,假设以下服务:
@Service
public class PersonnelService {
@Autowired
private PersonnelRepository repository;
public long save(Personnel entity) {
return repository.save(entity);
}
}
如果我在应用程序中有上述代码,在将已启用
字段添加到组织
后,我应该将上述方法更改为:
@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或类似的东西,并检测何时对对象进行修改,并且该对象有一个类型为
组织的字段
检查已启用
值?我假设您正在使用spring数据jpa或spring数据rest来实现更新。如果是这样,则可通过以下方式实现:
创建批注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;
}
}
现在在存储库中执行以下操作
@Override
@PreAuthorize("@updateIfTrueService.canUpdate(#user)")
User save(@Param("user")User user);
在组织上定义一个
@Where
,该组织根据启用的属性进行筛选。这样,残疾人组织就看不见了。
@Override
@PreAuthorize("@updateIfTrueService.canUpdate(#user)")
User save(@Param("user")User user);