英文:
How to make a custom annotation for trimmed field in entities?
问题
在Spring Boot和Java 8中,有多个模型:DTO、实体、ViewModels等,但需要获取和保存个人描述,而描述需要修剪值,例如:
@Size(min=0, max=1024)
private String description;
public String getDescription() {
return ((this.description != null) ? this.description.trim() : null);
}
public void setDescription(String description) {
this.description = ((description != null) ? description.trim() : null);
}
我创建了一个自定义注解 @Trimmed
来实现自动化,如下所示:
@Trimmed
@Size(min=0, max=1024)
private String description;
我尝试创建接口和切面:
Trimmed.java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Trimmed {
}
TrimmedAspect.java
@Aspect
@Component
public class TrimmedAspect {
@Around(" @annotation(Trimmed)")
public Object requestIntercept ...
}
但是,如何创建切面呢?在互联网上可以找到使用函数和类声明的示例,但在获取和设置值时没有涉及字段。
如何实现这一点?
英文:
In Spring Boot and Java 8, have multiple models: DTOs, Entities, ViewModels, etc, but need get and save the description of a person, but the description need trim the value, by example:
@Size(min=0, max=1024)
private String description;
public String getDescription() {
return ((this.description != null) ? this.description.trim() : null);
}
public void setDescription(String description) {
this.description = ((description != null) ? description.trim() : null);
}
I make a custom annotation like as @Trimmed
for automatize it like as:
@Trimmed
@Size(min=0, max=1024)
private String description;
I try make the interface and the aspect:
Trimmed.java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Trimmed {
}
TrimmedAspect.java
@Aspect
@Component
public class TrimmedAspect {
@Around("@annotation(Trimmed)")
public Object requestIntercept ...
}
But, how to make the aspect? in the internet can find examples using functions and class declarations but no fields when get and set values.
How to can made this?
答案1
得分: 1
我刚刚使用AOP创建了一个示例自定义注释,在我的组件"Event"负责此操作:我刚刚尝试了这段代码,也许它会有所帮助:它将在用户创建后执行。
@AfterReturning(value = "execution(* your.package..*(..))", returning = "retVal")
public void requestIntercept(JoinPoint pjp, Object retVal) throws JsonProcessingException {
//----- 在这里进行你的实现
}
英文:
I just made an example custom annotation with AOP, in my component Event responsible for this: I just tried this code maybe it helps: it will be executed after the user is created
@AfterReturning(value = "execution(* ypour.package..*(..))", returning = "retVal")
public void requestIntercept(JoinPoint pjp, Object retVal) throws JsonProcessingException {
//----- your implementation here
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论