Java Web Common Annotations

Java SE

@Deprecated // programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.
@FunctionalInterface
@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

Spring

Bean declaration

@Component
@Controller
@Service
@Repository

Make a bean belong to a particular profile

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

Bean injection

@Autowired
@Resource

Specify injected bean name

@Qualifier("specificBeanName")

Bean initMethod and destroyMethod

@PostConstruct
public void init() {}
@PreDestroy
public void destroy() {}

Configurations

@Configuration
@Bean
@ConditionalOnBean
@ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnResource
@ConditionalOnWebApplication
@ConditionalExpression
@Conditional

Configuration file properties

@PropertySource

@PropertySource("classpath:my.properties")
public class MyProperties {}

@ConfigurationProperties

@ConfigurationProperties(prefix = "config.path")
@Configuration
@EnableConfigurationProperties
@Data
public class MyProperties {}
@Value("${databaseName}")
private String databaseName;

Spring MVC

Request

@Controller
@RestController
@RequestMapping
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

Request Information

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

Response

@ResponseBody
@ResponseHeader
@ResponseStatus

Convert Request Parameter Types

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

Data Validation

@Valid
@Validated(groupClass)

Data Validation Constraints Annotations

See JavaEE Validation Constraints Annotations

Exception Handling

@ExceptionHandler

Spring Data Access

@Transactional(rollbackFor=Exception.class)

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

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Spring Security

@EnableWebSecurity

Spring Boot

Spring boot basic configuration

@SpringBootApplication
  • @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

@MapperScan

For example

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

Wildcard

  • *: 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.
@Null
@Size // The annotated element size must be between the specified boundaries (included).
@Pattern // The annotated CharSequence must match the specified regular expression.
@Email

validate number

@Digits
@Min
@Max
@DecimalMax
@DecimalMin
@Positive
@PositiveOrZero
@Negative
@NegativeOrZero

validate datetime

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

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

Jackson

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

@JsonPropertyDescription

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)

@JsonValue
public String getName() {
return name;
}

For more details refer to Jackson Annotations

Hibernate

@Entity
@Table
@Id
@GeneratedValue

MyBatis-Plus

Specify Table name

@TableName("t_user")

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

@TableField("`column`")
private String column;

Logic delete

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

For more details refer to MyBatis-Plus Annotations

Lombok

POJO

@Data
@Getter/@Setter
@ToString
@ToString(callSuper = true)
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
@EqualsAndHashCode
@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");
this.name = person.getName();
}

Result code

public NonNullExample(@NonNull Person person) {
super("Hello");
if (person == null) {
throw new NullPointerException("person is marked @NonNull but is null");
}
this.name = 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 = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
}

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

@SneakyThrows(UnsupportedEncodingException.class)
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.

@Log
@Log4j
@Log4j2
@Slf4j
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);

Others

@Value
@Synchronized
@With
@Getter(lazy=true)
@RequiredArgsConstructor(onConstructor_ = @Autowired)

For more details refer to Lombok features.

You can rolling Lombok Back with Delombok tool.