Custom annotations and common annotations in java

I. principle of annotation

II. User defined annotation

III. common notes

1.@ControllerAdvice

As the name suggests, the enhanced version of the controller, annotated on the class, has a faceted function that can handle all requests or exceptions accordingly. For example, cooperate with @ ExeptionHandler to handle exceptions in the system according to the exception type. For example, @ ModelAttribute processing of data is performed on the request before executing the request method, so that all requests have certain data. For example, combine @ InitBinder to screen the attributes with the same name, such as a.nam/b.name.

@ControllerAdvice
@Order(-2147483648) --statement bean The order of use, not the order of loading; The smaller the value, the higher the priority
public class HsGlobalExceptionHandler {
@ExceptionHandler({IllegalArgumentException.class})
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public HsErrorRsp handle(IllegalArgumentException exception) {
    LOGGER.error("Illegal argument exception.", exception);
    String errorMsg = this.messageSourceUtil.getMessage("rtd.00101102");
    return HsErrorRsp.builder().errorCode("rtd.00101102").errorMsg(errorMsg).build();
}

}

2.@PostConstruct

Called when the container is started to load the servlet. The specific time is after calling the construction method of the main servlet and before the init method; In addition, when this annotation modifies a method, the call time is after the construction method of the current class and @ Autowired injection; It can be seen from the above that the bean in the project is created in the construction method of sevlet.

The method modified by this annotation can only be loaded once, and the return value must be void and non static

Usage scenario: it can be seen from the above that this annotation is often used for processing after injecting instances into classes.

@Autowired
private RequestMappingHandlerAdapter adapter;

public HsOroasBeanConfig() {
}

①@PostConstruct
public void injectSelfMethodArgumentResolver() {
    List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList();
    argumentResolvers.add(this.hsFormPropertyAnnotationResolver());
    argumentResolvers.addAll(this.adapter.getArgumentResolvers());
    this.adapter.setArgumentResolvers(argumentResolvers);
}

@Primary
@Bean
public HsFormPropertyAnnotationProcessor hsFormPropertyAnnotationResolver() {
    return new HsFormPropertyAnnotationProcessor(false);
}

②@PostConstruct It can also be written in the main startup class to set the time zone
@PostConstruct
void started() {
    // Set the default Spring time zone to UTC
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}

3.@SpringBootApplication

When setting on the main startup, it should be noted that the scanBasePackage attribute will load beans according to the writing order of its value. When encountering some common processors, the beans will be matched first and then loaded. Once they are matched, the previous bean processor will not execute.

And when introducing other jar packages, specify to scan the classes in other packages

@SpringBootApplication(scanBasePackages = {"com.huawei.workflowmgnt.*", "com.huawei.ei.oroas.common.*"})

4.@ModelAttribute

It acts on the method and processes the parameters before reaching the controller.

Acting on the get request, it means that this parameter may obtain values from three places:

  1. Request parameter with the same name
  2. Path variable name with the same name
  3. model property with the same name
public ResponseEntity<List<AreaInfo>> searchAreas(@ModelAttribute @Validated ListAreasOption option) {

}
@HsFormProperty("sort_by") --------Put parameters into map In order to put it in model in
@Pattern(regexp = "name|create_time", message = ErrorCode.DATASOURCE_SORT_BY_ERROR)
private String sortBy = "name";

5.@Valid and @ valued

Annotations on control method parameters and parameters on entity classes on control method parameters

Make other annotation verification in the entity class work, and pay attention to cascading

@Valid verifies the entity class as a whole, @ Validated can be verified in groups

@NotNull(groups = BasicInfo.class) @Size(min = 4, max = 15, groups = BasicInfo.class)

private String password;

@NotBlank(groups = BasicInfo.class)

private String name;

@Min(value = 18, message = "Age should not be less than 18", groups = AdvanceInfo.class) private int age;

@NotBlank(groups = AdvanceInfo.class)

private String phone;

6.@Configuration -- --@Bean --@Primary

@Configuration is the original applicaitoncontext XML configuration file, you can configure bean s, import resource files, and wait

7.@ConfigurationProperties --@Value

@ConfigurationProperties reads the contents of yaml configuration file, acts on methods and classes, acts on methods / classes, and automatically maps parameters and configurations, name_class=nameClass

@Value

Only a single profile content can be mapped, and complex types of mapping, such as map and entity class, are not supported

8.@Bean @Primary

@Primary: when an interface has multiple implementations, this annotation can make it load preferentially

@Qualifier specifies which bean to use. When it exists with @ Primary, it has higher priority

9.@JsonProperty --@JsonIgnore --@JsonIgnoreProperties --@JsonInclude

@JsonProperty

Used in deserialization to map json data to class properties

@JsonComponent

Used during serialization and marked on the returned java class

@JsonInclude

@JsonInclude(JsonInclude.Include.NON_NULL)

When it modifies a class or a property, when its property is null, it is returned without serialization, that is, there is no such property

@JsonIgnore

Modifier attribute. This attribute is not converted when json is converted

@JsonIgnoreProperties

Modify the class. When the json attribute is more than the attribute in the class, it will not report an error; It works naturally when there are few json attributes

@JsonFormat

Modify attributes to help convert time and date formats

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

@JsonValue

?????????????????????

@JsonCreatror

????????????????

10.@Data --@Builder --@AllArgsConstructor --@NoArgsConstructor --@Log4j/@Slf4j

@Data: get/set/hashcode/equal/toString

@AllArgsConstructor provides a full parameter constructor

@NoArgsConstructor provides a parameterless constructor

@EqualsAndHashCode is annotated on the class and provides the corresponding equals and hashCode methods

@Log4j/@Slf4j: Note: on the class, the corresponding Logger object is provided, and the variable name is log

@Builder decorated class, which is equivalent to internally generating a static internal class; Yes, class builder. name(). ID () is a cascading operation

@Single modifier attribute, used in combination with @ Builder, can assign cascade values to collection class attributes, class Builder. name(1). name(2)

11.@RequestBody --@ResponseBody

@The return value of the method annotated with RequestBody will be parsed by the View. The method annotated with @ ResponseBody will not be parsed by the View, but directly convert the java object into json and put it into the return body

12.@Param

It is provided by mybatis and used in mapper class and mapper The annotation of parameters is passed in the middle of XML. Multiple @ Param parameters can be used in a method

13.@RestController = @Controller+@ResponseBody


 

 

Added by tyr_82 on Fri, 21 Jan 2022 05:27:40 +0200