Java Web Common Annotations

Java SE

@Deprecated // programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.
@Override // Indicates that a method declaration is intended to override a method declaration in a supertype.
@SuppressWarnings // Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element).
@SafeVarargs // A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.

Spring Projects


Bean declaration


Make a bean belong to a particular profile

// Only can contains one !string. Can't be like {"!dev","!test"}

Bean injection


Specify injected bean name


Bean initMethod and destroyMethod

public void init() {}
public void destroy() {}



Configuration file properties


public class MyProperties {}


@ConfigurationProperties(prefix = "config.path")
public class MyProperties {}
private String databaseName;

Spring MVC



Request Information

@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date datetime
@RequestParam @DateTimeFormat(pattern = "HH:mm:ss") LocalTime time



Convert Request Parameter Types

* This method used in your Controller,
* or you can put the method in your BaseController.
public void initBinder(WebDataBinder binder)
// Convert field type from string to Date
binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
public void setAsText(String text)
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(YourEnum.class, new YourEnumConverter());

Data Validation


Data Validation Constraints Annotations

See JavaEE Validation Constraints Annotations

Exception Handling


Spring Data Access


By default all RuntimeExceptions rollback transaction whereas checked exceptions don’t. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters: @Transactional(rollbackFor=Exception.class). This will rollback transaction after throwing any exception.

Programatically and manually roll back


Spring Security


Spring Boot

Spring boot basic configuration

  • @SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration
  • @Configuration: This annotation marks a class as a Configuration class for Java-based configuration. This is particularly important if you favor Java-based configuration over XML configuration.
  • @ComponentScan: This annotation enables component-scanning so that the web controller classes and other components you create will be automatically discovered and registered as beans in Spring’s Application Context.
  • @EnableAutoConfiguration: This annotation enables the magical auto-configuration feature of Spring Boot, which can automatically configure a lot of stuff for you.

Scan MyBatis mappers


For example

@MapperScan({"com.demo.dao", "com.demo.modules.**.dao"})


  • *: wildcard for one directory
  • **: wildcard for multiple level directory path

Java EE

Validation Constraints

validate object or string

@NotNull // a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty
@NotEmpty // a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null and its size/length is greater than zero
@NotBlank // a constrained String is valid as long as it's not null and the trimmed length is greater than zero.
@Size // The annotated element size must be between the specified boundaries (included).
@Pattern // The annotated CharSequence must match the specified regular expression.

validate number


validate datetime

@Future // The annotated element must be an instant, date or time in the future.
@Past // The annotated element must be an instant, date or time in the past.

For more details refer to Java EE 8 javax.validation.constraints annotations


JSON Serialization

Update format of serialized JSON value from Date type

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;

Update field name of serialized JSON

@JsonProperty(value = "user_password")
private String userPassword;

Ignore properties for JSON serialization

@JsonIgnore // for field
@JsonIgnoreProperties({"fieldname1", "fieldname2"}) // for POJO class
@JsonInclude // annotation used to define if certain "non-values" (nulls or empty values) should not be included when serializing

Serialize Enum to JSON String

@JsonSerialize(using = NameValueEnumSerializer.class)
public enum Type {

Property documentation, metadata


JSON Deserialization

Ignore Unknown Fields

@JsonIgnoreProperties(ignoreUnknown = true)

Convert JSON String to Date

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@DateTimeFormat(pattern = "HH:mm:ss")
private LocalTime alertTime;

Convert JSON String to Enum field (Note: The @JsonValue only deserialize for @RequestBody fields)

public String getName() {
return name;

For more details refer to Jackson Annotations




Specify Table name


Specify primary key

@TableId(value = "id", type = IdType.AUTO)

Specify field is not as a column of table of database

@TableField(exist = false)

When field name same with keywords of database need use backquote to avoid SQL execution error

private String column;

Logic delete

@TableLogic(value = "0", delval = "1")
private Integer deleteFlag;

For more details refer to MyBatis-Plus Annotations



@ToString(callSuper = true)
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
@Builder // User.builder().name("Jack").build()
  • @Data: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor.

Generate a null-check statement

public NonNullExample(@NonNull Person person) {
super("Hello"); = person.getName();

Result code

public NonNullExample(@NonNull Person person) {
if (person == null) {
throw new NullPointerException("person is marked @NonNull but is null");
} = person.getName();

Automatic resource management: Call your close() methods safely with no hassle.

public static void main(String[] args) throws IOException {
@Cleanup InputStream in = new FileInputStream(args[0]);
@Cleanup OutputStream out = new FileOutputStream(args[1]);
byte[] b = new byte[10000];
while (true) {
int r =;
if (r == -1) break;
out.write(b, 0, r);

To sneakily throw checked exceptions without actually declaring this in your method’s throws clause

public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");

Result code

public String utf8ToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw Lombok.sneakyThrow(e);

Annotate any class with a log annotation to let lombok generate a logger field.

private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());

private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);

private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);

private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);


@RequiredArgsConstructor(onConstructor_ = @Autowired)

For more details refer to Lombok features.

You can rolling Lombok Back with Delombok tool.