SoFunction
Updated on 2025-03-08

Common annotations for Spring Boot (classic dry goods)

Spring Boot

1.Why use Spring Boot

Because of Spring, SpringMVC requires a large number of configuration files (xml files)

Various objects are also required to place the used objects into the spring container before the objects can be used.

Other framework configuration rules need to be understood.

It is equivalent to Spring+SpringMVC that does not require configuration files. Common frameworks and third-party libraries have been configured.

Just take it and use it.

High development efficiency and much more convenient to use.

1. What is Spring Boot

Spring Boot is a fast development framework that quickly integrates some commonly used third-party dependencies (through the Maven child father project), simplifies the XML configuration, all in annotation form, built-in Http servers (Jetty and Tomcat), and finally executes them in Java applications.

2. Common Spring annotations

Common Annotations for Spring (absolutely classic)

3. Common annotations for Spring Boot

1、@SpringBootApplication

Alternatives @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan

2、@ImportAutoConfiguration

Import configuration classes, usually used when doing tests, @EnableAutoConfiguration is preferred.

3、@SpringBootConfiguration

Alternative @Configuration

4、@ImportResource

Import resources into container

5、@PropertySource 

Import properties files

6、PropertySources

Collection of @PropertySource

7、@Role

The bean role is defined as ROLE_APPLICATION (default value), ROLE_SUPPORT (working role), ROLE_INFRASTRUCTURE (backend role, user has no feelings)
8、@Scope

Specify the scope of the bean, default singleton, others include prototype, request, session, and globalSession

9、@Lazy

Make the bean lazy loading and cancel the bean pre-initialization.

10、@Primary

When multiple bean candidates appear during automatic assembly, the bean annotated as @Primary will be the preferred one, otherwise an exception will be thrown.

11、@Profile

Specify the environment under which the bean is activated

12、@DependsOn

The current class will be registered only after the dependent bean is registered. If the dependent bean does not exist, an error will be reported. Used to control the order of bean loading

13、@PostConstruct

After all the properties of the bean are injected, the annotation method is executed to initialize it.

14、@Autowired

By default, assemble by type. If we want to use assemble by name, we can use it in conjunction with the @Qualifier annotation.

15、@Lookup

According to the type returned by the method, remove the corresponding one from the container

16、@Qualifier

Declare the bean name, and beans can be loaded according to the bean name

17、@Required

Check the bean's attribute setXXX() method, and requires that the attributes must be configured in the configuration stage.

18、@Description

Add a text description of the bean

19、@EnableAspectConfiguration

Start AspectJ automatic configuration

20、EnableLoadTimeWeaving

Dynamic enhancement of the startup class loader, implemented using instrumentation

21、@AutoConfigurationPackage

The package containing this annotation will be registered by AutoConfigurationPackages

22、@AutoConfigureBefore

Load before the specified configuration class is initialized

23、@AutoConfigureAfter

Load after the specified configuration class is initialized

24、@AutoConfigureOrder

Specify the initialization order of configuration class. The smaller the initialization, the earlier it is.

25、@ModelAttribute

@ModelAttributeAnnotations can be applied to methods and method parameters.

(1) Use @ModelAttribute annotation for the method:

Annotated on the method@ModelAttributeThe method is used to add one or more attributes to the model. Such a method can accept@RequestMappingAnnotate the same parameter type, but it cannot be mapped directly to the specific request.

The @ModelAttribute method will be called first.

In the same controller, the annotation is@ModelAttributeThe method will actually be@RequestMappingThe method is called before. Here are a few examples:

@Controller
public class ModelAttributeController {
 
	@ModelAttribute
	public void init(Model model) {
		("@RequestMapping Method");
	}
 
	@RequestMapping("/model-attribute")
	public String get() {
		("@ModelAttribute method");
 
		return "model-attribute";
	}
 
}

You can use the @ModelAttribute annotation method to set common parameters of other @ReqeustMapping methods.

Use @ModelAttribute("key") to display the specified attribute name.

(2) @ModelAttribute and @RequestMapping annotations are on the same method

If the @ModelAttribute and @RequestMapping annotations are on the same method, then it means that the Model parameter is set separately for the request. The returned value at this time is the parameter value of the Model, not the jump address. The jump address is automatically converted according to the requested url. For example, in the following example, jumping to the page is not . And parameters can only be obtained in , but cannot be obtained in .

(3) Use @ModelAttribute annotation on method parameters

① Data binding

Annotated on method parameters@ModelAttributeIt shows that the value of the parameter of this method will be obtained from the model. If it is not found in the model, the parameter will be instantiated first and then added to the model. After the existence of the model,All parameters with matching names in the request will be filled into this parameter. This is called data binding in Spring MVC, a very useful feature that saves you time you need to manually convert these field data from tabular data every time.

② Use with BindingResult

use@ModelAttributeAfter data binding, you can useBindingResultReturn the data verification result. Data verification can be usedhibernate validationof@ValidTag orspring ValidatorVerification mechanism@ValidatedUse with BindingResult. Or customize the verification device to return the BindingResult object to perform verification. You can use Spring<errors>Form tags to display error messages on the same form.

@Valid Verifier:

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = )
public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) {
 
    if (()) {
        return "petForm";
    }
 
    // ...
 
}

@Validated Verifier:

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = )
public String processSubmit(@Validated @ModelAttribute("pet") Pet pet, BindingResult result) {
 
    if (()) {
        return "petForm";
    }
 
    // ...
 
}

Custom verifier:

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = )
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
 
    // Write a verification method yourself to handle the result object    new PetValidator().validate(pet, result);
    if (()) {
        return "petForm";
    }
 
    // ...
 
}

4. Selector

@Conditional, the component is registered only when all specified conditions are met
@ConditionalOnBean, the current bean is registered only when the bean is specified in the context. When used in a method, the default dependency class is the return type of the method
@ConditionalOnClass, the current bean is initialized when the specified class is on the classpath. When used in a method, the default dependency class is the return type of the method
@ConditionalOnCloudPlatform, only the configuration is registered on the specified cloud platform
@ConditionalOnExpression, register configuration when spel is specified
@ConditionalOnJava, register configuration when specifying java version
@ConditionalOnJndi
@ConditionalOnMissingBean, the current bean is initialized when the specified bean is not in the context. When used in a method, the default dependency class is the return type of the method
@ConditionalOnMissingClass, the current bean is initialized when the specified class is not on the classpath. When used in a method, the default dependency class is the return type of the method
@ConditionalOnNotWebApplication, you do not register the configuration in the web environment
@ConditionalOnProperty, whether the value in the configuration file is equal to the specified value, only if the configuration is equal is registered
@ConditionalOnResource, only the configuration is registered on the classpath
@ConditionalOnSingleCandidate, the configuration is registered when there is only one candidate bean in the context
@ConditionalOnWebApplication, the configuration is registered in the web environment

V. Cache

@EnableCaching, enable cache configuration, support subclass proxy or AspectJ enhancement
@CacheConfig, under a class, provides public cache configuration
@Cacheable, put the return value of all methods on the method and class, cache the method or class
@CachePut, execute the method first every time, and then put the result into the cache
@CacheEvict, delete cache
@Caching, you can configure @Cacheable, @CachePut, @CacheEvict

6. Timer

@EnableScheduling, enable the timing task function
@Scheduled, execute method according to the specified execution cycle
@Schedules, contains multiple @Scheduled, can run multiple cycle configurations simultaneously
@EnableAsync, enable the ability to execute asynchronously, and find methods that require asynchronous execution through @Async or custom annotations. Customize Executor and exception handling by implementing the getAsyncExecutor() and getAsyncUncaughtExceptionHandler() methods of the AsyncConfigurer interface.
@Async, marking method is executed in an asynchronous thread

7. Inject configuration files properties

@EnableConfigurationProperties, start the @ConfigurationProperties function
@ConfigurationProperties, automatically inject the contents in the properties file into the corresponding properties of the bean
@DeprecatedConfigurationProperty, used on the getter() method of the configuration file, marks the field has expired and prompts for the replaced field. Generally used for spring-boot-configuration-processor.
@NestedConfigurationProperty, marked on the field of the configuration file, prompt spring-boot-configuration-processor, configuration contains nested configurations.
Provides configuration meta information, and there will be syntax prompts when writing properties configuration. Introduce spring-boot-configuration-processor project into the project, the @ConfigurationProperties annotation will be scanned and automatically generated

8. Jpa

1、@Entity ,@Table(name="")

It indicates that this is an entity class, which is generally used for jpa. These two annotations are used together, but if the table name and entity class name are the same, @Table can be omitted.

2、@MappedSuperClass

Based on the idea of ​​code reuse and model separation, jpa's @MappedSuperClass annotation is used in project development to encapsulate multiple attributes of entity classes into different non-entity classes. For example, id is needed in database tables to represent the number. id is the general attribute of these mapping entity classes. It is handed over to jpa to produce the primary key id number uniformly. Then use a parent class to encapsulate these general attributes and identify them with @MappedSuperClass.

Notice:

  • The class marked @MappedSuperClass will not be a complete entity class, it will not map to the database table, but its properties are mapped to the database fields of its subclasses.
  • Classes marked @MappedSuperClass cannot be marked @#Entity or @Table annotations, nor do they need to implement serialized interfaces.

3、@NoRepositoryBean

Generally, it is used as the parent class's repository. With this annotation, spring will not instantiate the repository.

4、@Column

If the field name and column name are the same, it can be omitted.

5、@Id

Indicates that this property is the primary key.

6、@Transient

Indicates that this property is not a map to a field in the database table, and the ORM framework will ignore this property.

If an attribute is not a field map of a database table, be sure to annotate it as @Transient, otherwise, the ORM framework annotates it as @Basic by default.

7、@Basic

@Basic is the simplest type when mapping entity classes with database fields.

Types support Java basic types (byte, short, int, long, float, double, char, boolean), wrapper classes, enumeration classes, and types that implement serializable interfaces.

@basic annotation has two properties:

  • Fetch uses to specify the loading mechanism of attributes

There are two options: EAGER (instant load, default value) and LAZY (lazy load). Instant load means that the property value must be loaded when the object is instantiated. Lazy load means that the object is not loaded when the object is instantiated, and it is only loaded when the property is called.

  • optional is used to specify whether the attribute is nullable

There are two options: true (nullable, default) and false

If you do not add @Basic annotation to your entity class, it will also automatically add @Basic and use the default value.

8、@JsonIgnore

When the entity class returns data to the foreground, it is used to ignore properties or interfaces that you do not want to pass to the foreground.

There are certain operation and maintenance fields in the bean entity. When returning information to the foreground, you do not want to return the corresponding values ​​together. At this time, you can add @JsonIgnore to the corresponding attribute, or you can add annotation @JsonIgnoreProperties(value="{password}")

9、@JoinColumn、@OneToOne、@OneToMany、@ManyToOne

9. Import configuration files

1、@PropertySource

Introduce a single properties file:

@PropertySource(value = {"classpath:xxxx/"})

Introduce multiple properties files

@PropertySource(value = {"classpath:xxxx/","classpath:xxxx/"})

2. @ImportResource import xml configuration file

It can be divided into two modes: the classpath of the relative path and the file of the absolute path.

Note: Single files can be written without values ​​or locations.

Value: Use @Value annotation to retrieve the value in the configuration file

@Value("${propertiesKey in}")
 
private String xxx;

3. @Import import additional configuration files

The function is similar to XML configuration and is used to import configuration classes. You can import configuration classes with @Configuration annotation or implement ImportSelector/ImportBeanDefinitionRegistrar.

@SpringBootApplication
@Import({})
public class DemoApplication {
    public static void main(String[] args) {
        (, args);
    }
}

10. Business Notes

@Transactional

In Spring, there are two implementations of transactions, namely programmatic transactions and declarative transactions.

Programming transactions:

Programmatic transactions use TransationTemplate or directly use the underlying PlatformTransactionManager. For programming transactions, spring recommends using TransationTemplate.

Declarative transactions:

Based on AOP, its essence is to intercept the method before and after, and then create or add a transaction before the target method begins. After executing the target method, the transaction can be submitted or rolled back according to the execution situation. Transaction operations can be performed through @Transactional, which is faster and simpler. Recommended use.

11. Spring Cloud

1、@EnableEurekaServer

Used on the springboot startup class, it means that this is an eureka service registration center;

2、@EnableDiscoveryClient

Used on the springboot startup class, it means that this is a service and can be found by the registry;

3、@LoadBalanced

Turn on load balancing capability;

4、@EnableCircuitBreaker

Used in the startup class, turn on the circuit breaker function;

5、@HystrixCommand(fallbackMethod=”backMethod”)

Used in the method, fallbackMethod specifies the break callback method;

6、@EnableConfigServer

Used on the startup class, it means that this is a configuration center and enables Config Server;

7、@EnableZuulProxy

Enable zuul route and use it on the startup class;

8、@SpringCloudApplication

  • @SpringBootApplication
  • @EnableDiscovertyClient
  • @EnableCircuitBreaker

These are SpringBoot annotations, Registration Service Center Eureka annotations, and Circuit Breaker annotations.

For SpringCloud, these are three annotations that each microservice must have, so the annotation collection of @SpringCloudApplication was launched.

9、@ConfigurationProperties

(1) Introduction to @ConfigurationProperties Annotation

The Spring source code uses a lot of ConfigurationProperties annotations, for example, it is obtained from this annotation. By using it in conjunction with other annotations, the on-demand configuration of the bean can be realized.

This annotation has a prefix attribute, which binds the configuration in the configuration file through the specified prefix. The annotation can be placed on the class or on the method.

(2) Code example

=jdbc:mysql://127.0.0.1:8888/test?useUnicode=false&autoReconnect=true&characterEncoding=utf-8
=root
=root
-class-name=
=
@ConfigurationProperties(prefix = "")
@Component
public class DatasourcePro {
    private String url;
    private String username;
    private String password;
    // The configuration file is driver-class-name, and the name can be bound to the camel    private String driverClassName;
    private String type;
 
    ...
}

The above code implements the assignment of attributes through configuration files.

(3) Things to note

  • @ConfigurationProperties and @value have the same functions, but the writing of @ConfigurationProperties is more convenient;
  • @ConfigurationProperties The POJO class is named strictly because it must be consistent with the suffix name of prefix, otherwise the value will not be bound. The special suffix name is "driver-class-name" and other horizontal bars. The naming rules in POJO areUnderline to camelThe binding can be successful, so it is "driverClassName".

This is the end of this article about Spring Boot's common annotations (classic dry goods). For more relevant Spring Boot's common annotations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!