@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
Make a bean belong to a particular profile
1
@Profile("dev")
1
@Profile({"dev","test"})
1 2
// Only can contains one !string. Can't be like {"!dev","!test"} @Profile("!dev")
@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
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 publicvoidinitBinder(WebDataBinder binder) { // Convert field type from string to Date binder.registerCustomEditor(Date.class, newPropertyEditorSupport() { @Override publicvoidsetAsText(String text) { setValue(DateUtils.parseDate(text)); } }); }
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.
@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
validate object or string
1 2 3 4 5 6 7
@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
@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
@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
@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
publicNonNullExample(@NonNull Person person) { super("Hello"); this.name = person.getName(); }
Result code
1 2 3 4 5 6 7
publicNonNullExample(@NonNull Person person) { super("Hello"); if (person == null) { thrownewNullPointerException("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
publicstaticvoidmain(String[] args)throws IOException { @CleanupInputStreamin=newFileInputStream(args[0]); @CleanupOutputStreamout=newFileOutputStream(args[1]); byte[] b = newbyte[10000]; while (true) { intr= 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) { returnnewString(bytes, "UTF-8"); }