Common annotations for Spring family framework

Reflection related

@Target

Spring core annotations specify the java types that the custom annotation MyAnno can be applied to , thereby providing compile-time type checking and error detection.

When specifying the type, use the specific enumeration value under the enumeration class ElementType, including:
ElementType.TYPE: indicates that MyAnno is suitable for classes, interfaces, and enumerations.
ElementType.FIELD: Indicates that MyAnno is applicable to fields (member variables).
ElementType.METHOD: Indicates that MyAnno is suitable for methods.
ElementType.PARAMETER: Indicates that MyAnno is suitable for method parameters.
ElementType.CONSTRUCTOR: Indicates that MyAnno is applicable to the constructor.
ElementType.LOCAL_VARIABLE: Indicates that MyAnno is suitable for local variables.
ElementType.ANNOTATION_TYPE: Indicates that MyAnno is suitable for annotation types.
ElementType.PACKAGE: Indicates that MyAnno is suitable for packages.

@Retention

Specify when to retain the custom annotation MyAnno . There are three retention strategies:

  1. RetentionPolicy.SOURCE: Source code level retention. This retention policy means that the annotations are only visible in the source code . The compiler will discard these annotations during compilation and will not be included in the compiled bytecode. This annotation is mainly used to provide compile-time checks and warnings and will not have any impact on runtime.
  2. RetentionPolicy.CLASS: Class level retention. This retention policy means that annotations will be retained in the compiled bytecode, but will not be accessible at runtime . This is the default retention policy, which defaults to CLASS if no retention policy is explicitly specified on the annotation. Such annotations can be used for compile-time processing, such as using reflection to process annotations.
  3. RetentionPolicy.RUNTIME: Runtime level retention. This retention policy means that annotations will be retained in the compiled bytecode and can be accessed and used through the reflection mechanism at runtime . This annotation can be used to perform certain operations at runtime, such as configuration, dependency injection, dynamic proxying, etc.

Example
definition of custom annotation MyAnno

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    // 注解的成员声明
    // ...
}

Use custom annotation MyAnno

@MyAnnotation(value=")
public class Person extends xxx implements xxx{}

Startup class related

Universal

@ComponentScan

Annotation @ComponentScanis a core annotation in the Spring framework, which is used to tell Spring to scan components under which packages and register them in the context of the application. It can be applied to configuration classes ( @Configurationclasses annotated with ) or startup classes ( @SpringBootApplicationclasses annotated with ).

@ComponentScanThe following usages are provided:

  1. Scan specified packages:
    You can use @ComponentScanthe annotated valueor basePackagesattribute to specify the packages to be scanned. One or more package names can be passed as arguments to these properties, as follows:
@ComponentScan(value = "com.example.package")
// 或
@ComponentScan(basePackages = {
    
    "com.example.package1", "com.example.package2"})

This will cause Spring to scan the specified package and its sub-packages and register all components (with @Componentannotations and their derived annotations, such as @Controller, @Service, @Repositoryetc.).

  1. Scan the package where the specified class is located:
    In addition to directly specifying the package name, you can also use the attribute @ComponentScanof the annotation basePackageClassesto specify one or more classes, and Spring will scan the packages where these classes are located. For example:
@ComponentScan(basePackageClasses = {
    
    MyController.class, MyService.class})

This will scan the package MyControllerand MyServicesubpackages where the and classes are located.

  1. Automatically detect and register components:
    @ComponentScanAnnotations will automatically detect and register @Componentcomponents with and its derived annotations by default. If you need to automatically detect and register other types of components, you can use includeFiltersthe attribute. For example, to automatically register components with @Controllerand @Repositoryannotations, you can configure it like this:
@ComponentScan(basePackages = "com.example.package", includeFilters = {
    
    
    @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {
    
    Controller.class, Repository.class})
})

typeSet the filter type to via the property FilterType.ANNOTATIONand specify the annotation types to include.

  1. Exclude specific components:
    If you want to exclude a specific type of component, you can use excludeFiltersthe attribute. For example, to exclude @Configurationcomponents with an annotation, you can configure it like this:
@ComponentScan(basePackages = "com.example.package", excludeFilters = {
    
    
    @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)
})

typeSet the filter type to via the property FilterType.ANNOTATIONand specify the annotation types to exclude.

The above are @ComponentScancommon uses of annotations. It can help Spring automatically scan and register components, so that we can easily use dependency injection and other Spring features to develop applications.

Spring Cloud related

@EnableDiscoveryClient

Is an annotation in Spring Cloud used to enable service discovery client functionality . It is often used with a service registry (such as Eureka, Consul, Zookeeper, etc.) to register applications with the service registry and discover other services.

When using @EnableDiscoveryClientannotations, you need to ensure that the appropriate service discovery client dependency has been added to the project, such as spring-cloud-starter-netflix-eureka-client(for Eureka) or spring-cloud-starter-consul-discovery(for Consul).

The basic usage of using @EnableDiscoveryClientis as follows:

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDiscoveryClient
public class YourApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(YourApplication.class, args);
    }

}

By adding an annotation to the startup class of a Spring Boot application @EnableDiscoveryClient, the application will be marked as a service discovery client. It automatically interacts with the configured service registry and registers instances of the application with the registry. At the same time, it will also obtain information about other services from the registration center to make service calls when needed .

Please note that @EnableDiscoveryClientannotations are Spring Cloud's common service discovery annotations, providing integration capabilities with multiple service registries. You can also use more specific annotations, such as @EnableEurekaClient(Eureka Registry) or @EnableConsulClient(Consul Registry), if you only need to integrate with a specific service registry.

After using @EnableDiscoveryClientthe annotation, you can use the service discovery function in the application, such as making a service call through the service name, dynamically obtaining the list of service instances, and so on. The specific usage method will vary according to the specific service registry and Spring Cloud components, and you can configure and use it according to the selected registry and related documents.

@EnableFeignClients

@EnableFeignClientsis an annotation in Spring Cloud that enables Feign client functionality without having to manually write HTTP requests and process responses . Feign is a declarative HTTP client that simplifies RESTful API calls between services.

When using @EnableFeignClientsannotations, you need to ensure that the appropriate Feign dependency has been added to the project, for example spring-cloud-starter-openfeign.

Basic usage
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableFeignClients
public class YourApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(YourApplication.class, args);
    }

}

By adding an annotation on the startup class of a Spring Boot application @EnableFeignClients, the application will be marked to use the Feign client. It will automatically scan the specified package, find @FeignClientinterfaces with annotations, and generate the corresponding proxy class.

Next, you need to create an @FeignClientinterface marked with an annotation that specifies the name or URL of the target service to be called. For example:

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "your-service")
public interface YourServiceClient {
    
    

    @GetMapping("/api/resource")
    String getResource();

}

In the above example, @FeignClientthe annotation's nameattribute specifies the name of the service to be called. YourServiceClientThe methods in the interface define the specific API to be called.

Now, you can YourServiceClientinject the interface into other components and use it to call the target service's API. Feign automatically handles serialization and deserialization of requests and responses, and uses features such as load balancing.

Note that @EnableFeignClientsannotations need to be used in conjunction with other Spring Cloud components such as a service registry to enable features such as service discovery and load balancing in the Feign client. You need to configure and integrate appropriately based on your specific needs and configurations.

Request related

@PathVariable

In Spring MVC, the @PathVariable annotation can be used to handle RESTful-style URLs, where part of the URL contains variable path parameters. By using the @PathVariable annotation, you can extract these path parameters and pass them to the controller method for processing.

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
    // 根据 id 查询用户
    User user = userService.getUserById(id);
    
    if (user != null) {
        return ResponseEntity.ok(user);
    } else {
        return ResponseEntity.notFound().build();
    }
}

@Data

Used to automatically implement the set and get methods of class object variables, class object variables are suitable for packaging classes, non-basic data classes and non-generic classes , such as Integer, String, and custom ClassA

use

  1. IDEA installs [lombok] plugin
  2. Open the annotation processor in IDEA Settings

image.png

  1. Introduce lombok dependency in pom.xml
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
  1. Add @Data on the class declaration body that needs to automatically implement the set and get methods of class object variables
@Data
@ApiModel(value = "全局统一返回结果")
public class Result<T> {

    @ApiModelProperty(value = "返回码")
    private int resultCode;
    ...
}


Guess you like

Origin blog.csdn.net/weixin_45549370/article/details/132769176