Contents
  1. 1. Java SE
  2. 2. Spring Projects
    1. 2.1. Spring
    2. 2.2. Spring MVC
    3. 2.3. Spring Data Access
    4. 2.4. Spring Security
    5. 2.5. Spring Boot
  3. 3. Java EE
    1. 3.1. Validation Constraints
  4. 4. Jackson
    1. 4.1. JSON Serialization
    2. 4.2. JSON Deserialization
  5. 5. Hibernate
  6. 6. MyBatis-Plus
  7. 7. Lombok

Java SE

1
2
3
4
5
@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

1
2
3
4
@Component
@Controller
@Service
@Repository

Bean injection

1
2
@Autowired
@Resource

Specify inject bean name

1
@Qualifier("specificBeanName")

Bean initMethod and destroyMethod

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

Configurations

1
2
3
4
5
6
7
8
9
@Configuration
@Bean
@ConditionalOnBean
@ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnResource
@ConditionalOnWebApplication
@ConditionalExpression
@Conditional

Configuration file properties

1
2
@PropertySource
public class MySqlDriver {}
1
2
@Value("${databaseName}")
private String databaseName;

Spring MVC

Request

1
2
3
4
5
6
7
8
@Controller
@RestController
@RequestMapping
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

Request Information

1
2
3
4
5
@PathVariable
@RequestParam
@ModelAttribute
@RequestBody
@RequestHeader

Response

1
2
3
@ResponseBody
@ResponseHeader
@ResponseStatus

Convert Request Parameter Types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 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));
}
});
}
1
2
3
4
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(YourEnum.class, new YourEnumConverter());
}

Data Validation

1
2
@Valid
@Validated(groupClass)

Data Validation Constraints Annotations

See JavaEE Validation Constraints Annotations

Exception Handling

1
@ExceptionHandler

Spring Data Access

1
@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

1
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Spring Security

1
@EnableWebSecurity

Spring Boot

1
@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.

Java EE

Validation Constraints

1
2
3
4
5
6
7
@NotNull
@Null
@NotBlank // The annotated element must not be null and must contain at least one non-whitespace character.
@NotEmpty // The annotated element must not be null nor empty.
@Size // The annotated element size must be between the specified boundaries (included).
@Pattern // The annotated CharSequence must match the specified regular expression.
@Email
1
2
3
4
5
6
7
8
9
@Digits
@Min
@Max
@DecimalMax
@DecimalMin
@Positive
@PositiveOrZero
@Negative
@NegativeOrZero
1
2
3
4
@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

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

Update field name of serialized JSON

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

Ignore properties for JSON serialization

1
2
3
@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

1
2
3
@JsonSerialize(using = NameValueEnumSerializer.class)
public enum Type {
}

Property documentation, metadata

1
@JsonPropertyDescription

JSON Deserialization

Convert JSON String to Date

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

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

1
2
3
4
@JsonValue
public String getName() {
return name;
}

For more details refer to Jackson Annotations

Hibernate

1
2
3
4
@Entity
@Table
@Id
@GeneratedValue

MyBatis-Plus

Specify Table name

1
@TableName("t_user")

Specify primary key

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

Specify field is not as a column of table of database

1
@TableField(exist = false)

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

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

Logic delete

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

For more details refer to MyBatis-Plus Annotations

Lombok

POJO

1
2
3
4
5
6
@Data
@Getter/@Setter
@ToString
@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

1
2
3
4
public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName();
}

Result code

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}

Result code

1
2
3
4
5
6
7
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.

1
2
3
4
@Log
@Log4j
@Log4j2
@Slf4j
1
2
3
4
5
6
7
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

1
2
3
4
@Value
@Synchronized
@With
@Getter(lazy=true)

For more details refer to Lombok features.

You can rolling Lombok Back with Delombok tool.

Contents
  1. 1. Java SE
  2. 2. Spring Projects
    1. 2.1. Spring
    2. 2.2. Spring MVC
    3. 2.3. Spring Data Access
    4. 2.4. Spring Security
    5. 2.5. Spring Boot
  3. 3. Java EE
    1. 3.1. Validation Constraints
  4. 4. Jackson
    1. 4.1. JSON Serialization
    2. 4.2. JSON Deserialization
  5. 5. Hibernate
  6. 6. MyBatis-Plus
  7. 7. Lombok