简体   繁体   English

如何使用自定义注释在Spring Boot中隐藏带注释的字段?

[英]How to hide annotated fields in Spring Boot using custom annotations?

I have created custom annotations that I add to my Java class fields. 我创建了自定义注释,并将其添加到Java类字段中。 When I create object of that class, I want my custom annotated fields to have value: null or "" or "customAnnotation" For example: 创建该类的对象时,我希望自定义注释字段具有值:null或“”或“ customAnnotation”例如:

@Entity
public class User implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "address_id")
private Long id;

@MyCustomAnnotation
private String firstname;

private String lastname;
....

And when I create the object somewhere in the project: 当我在项目中的某处创建对象时:

User user = new User();
user.setFirstname("John");
user.setLastname("Smith");

I want it to be: 我希望它是:

String firstname = user.getFirstname() // firstname is "" or null
String lastname = user.getLastname()   // lastname is "Smith"

How to create method that will find all annotated fields in all classes in the project and do the same for all of them? 如何创建将在项目的所有类中找到所有带注释的字段并对其进行相同处理的方法? Where to store this method? 该方法在哪里存储? I am working on the Maven, Spring Boot project. 我正在从事Maven,Spring Boot项目。

At some point in your code you will have to implement something like this: 在代码中的某些时候,您将必须实现以下内容:

Class<User> obj = User.class;

if (obj.isAnnotationPresent(MyCustomAnnotation.class)) {
  //your business logic
}

Sensible places for something like this would be either immediately when creating users, when getting users (for whatever reason the annotation is being used) or at an interval in a timed routine. 诸如此类的明智位置可以是在创建用户时,在获得用户时(无论使用注释的任何原因)或在定时例程中间隔一定的时间。

edit: See this tutorial: https://www.mkyong.com/java/java-custom-annotations-example/ 编辑:请参阅本教程: https : //www.mkyong.com/java/java-custom-annotations-example/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM