假设这个类图:
我有一个名为 Organization
的类许多对象与此相关联。除了StoreHouse
之外还有很多对象和 Personnel
,但是为了有简单的类图,我没有将这些类放入图中(假设超过 1000 个类依赖于 Organization
类)。
现在,我想添加 enabled
字段到 Organization
类(class)。这很简单,没有任何问题。但在那之后,我想阻止所有业务点和服务使用 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);
}
}
而且由于这个 Action 非常耗时,改了1000多个类。
我想知道是否有一种方法可以在不改变业务点的情况下执行此操作,例如使用 Aspect 或类似的东西,并检测何时对对象进行修改并且它有一个类型为 Organization
的字段检查enabled
值(value)?
最佳答案
我假设你正在使用 spring data jpa 或 spring data 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;
}
}
注释要检查的实体。例如,具有以下注释的用户
@UpdateIfTrue("personnel.organization.enabled")
现在在存储库中执行以下操作
@Override
@PreAuthorize("@updateIfTrueService.canUpdate(#user)")
User save(@Param("user")User user);
关于java - 如何在不更改代码的情况下将限制应用于 spring/hibernate 企业应用程序中的所有业务点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45911909/