Spring Boot common annotations [detailed]

Spring Boot common annotations [detailed]

1. What is Spring Boot

Spring Boot is a rapid development framework, which quickly integrates some commonly used third-party dependencies (through the Maven sub-parent project), simplifies xml configuration, all in the form of annotations, built-in Http servers (Jetty and Tomcat), and finally uses Java applications The program is executed.

Two, Spring Boot common annotations

1、@SpringBootApplication

替代 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan

2、@ImportAutoConfiguration

Import configuration class, generally used when doing tests, normally @EnableAutoConfiguration is preferred

3、@SpringBootConfiguration

Alternative to @Configuration

4、@ImportResource

Import resources into the container

5、@PropertySource

Import properties file

6、PropertySources

Collection of @PropertySources

7、@Role

The bean role is defined as ROLE_APPLICATION (default value), ROLE_SUPPORT (auxiliary role), ROLE_INFRASTRUCTURE (background role, user has no sense)

8、@Scope

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

9、@Lazy

Make beans lazy loading, cancel bean pre-initialization.

10、@Primary

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

11、@Profile

Specifies the environment in which the bean is activated

12、@DependsOn

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

13、@PostConstruct

After all the properties of the bean are injected, the way of annotation annotation is executed for initialization

14、@Autowired

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

15、@Lookup

According to the type returned by the method, go to the container to fish out the corresponding

16、@Qualifier

Declare the bean name, and the bean can be loaded by the bean name

17、@Required

Check the bean's property setXXX() method, which requires that the property must have been configured during the configuration phase

18、@Description

Add text description of bean

19、@EnableAspectConfiguration

Start AspectJ auto-configuration

20、EnableLoadTimeWeaving

The dynamic enhancement function of the startup class loader is realized by using instrumentation

21、@AutoConfigurationPackage

The package containing this annotation will be registered by AutoConfigurationPackages

22、@AutoConfigureBefore

Load before the initialization of the specified configuration class

23、@AutoConfigureAfter

Loaded after the specified configuration class is initialized

24、@AutoConfigureOrder

Specify the initialization order of configuration classes, the smaller the initialization, the earlier

25、@ModelAttribute

The @ModelAttribute annotation can be applied to methods and method parameters.

(1) Use the @ModelAttribute annotation on the method:

The @ModelAttribute annotated on the method indicates that the function of the method is to add one or more attributes to the model. Such a method can accept the same parameter types as the @RequestMapping annotation, but cannot be directly mapped to a specific request.

The @ModelAttribute method will be called first.

In the same controller, the method annotated with @ModelAttribute will actually be called before the @RequestMapping method. Here are a few examples:

@Controller
public class ModelAttributeController {
    
    
 
	@ModelAttribute
	public void init(Model model) {
    
    
		System.out.println("@RequestMapping方法");
	}
 
	@RequestMapping("/model-attribute")
	public String get() {
    
    
		System.out.println("@ModelAttribute方法");
 
		return "model-attribute";
	}
}

You can use the @ModelAttribute annotated method to set the public 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 @ModelAttribute and @RequestMapping are annotated on the same method, then the representative sets the Model parameter separately for this request. The value returned at this time is the parameter value of Model, not the jump address. The redirected address is automatically converted according to the requested url. For example, the jump page in the following example is not HelloWorld.jsp but model-attribute.jsp. And the parameters can only be obtained in model-attribute.jsp, but not in demo.jsp.

(3) Use @ModelAttribute annotation on method parameters

① Data binding

The @ModelAttribute annotated on the method parameter indicates that the value of the method parameter will be obtained from the model. If not found in the model, the parameter will be instantiated first and then added to the model. After it exists in 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 the time of having to manually convert these field data from table data every time.

② Use with BindingResult

After using @ModelAttribute for data binding, you can use BindingResult to return data validation results. Data validation can use the @Valid tag of hibernate validation or @Validated of the spring Validator verification mechanism with BindingResult. Or customize the validator to return a BindingResult object for validation. You can display error messages on the same form via Spring's form tags.

@Valid Validator:

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

@Validated validator:

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

Custom validator:

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
    
    
 
    // 自己编写一个校验方法来处理 result 对象
    new PetValidator().validate(pet, result);
    if (result.hasErrors()) {
    
    
        return "petForm";
    }
 
    // ...
}

3. Selector

@Conditional, when the specified conditions are met, the component is registered
@ConditionalOnBean, the current bean is only registered when the specified bean is in the context. When used on a method, the default dependent class is the return type
@ConditionalOnClass of the method, and the current bean is only initialized when the specified class is on the classpath. When used in a method, the default dependent class is the return type of the method
@ConditionalOnCloudPlatform. Register and configure
@ConditionalOnExpression when specifying the cloud platform. Register and configure @ConditionalOnJava when specifying the spel to be true . Register and configure @ConditionalOnJndi @ConditionalOnMissingBean
when specifying the java version . Specify The current bean is only initialized when the bean is not in the context. When used on a method, the default dependent class is the return type @ConditionalOnMissingClass of the method, and the current bean is only initialized when the specified class is not on the classpath. When used in a method, the default dependent class is the return type of the method @ConditionalOnNotWebApplication. Register and configure @ConditionalOnProperty if it is not in the web environment. If the value in the configuration file is equal to the specified value, register and configure @ConditionalOnResource when they are equal. The specified resources are all in the classpath The configuration is registered on @ConditionalOnSingleCandidate, and the configuration is only registered when there is only one candidate bean in the context







@ConditionalOnWebApplication is registered and configured in the web environment

4. Cache

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

5. Timer

@EnableScheduling, enable the scheduled task function
@Scheduled, execute the method
@Schedules according to the specified execution cycle, including multiple @Scheduled, and can run multiple cycles at the same time Configure
@EnableAsync, enable the ability to execute asynchronously, and find it through @Async or custom annotations Methods that need to be executed asynchronously. Customize Executor and exception handling by implementing the getAsyncExecutor() and getAsyncUncaughtExceptionHandler() methods of the AsyncConfigurer interface.
@Async, mark the method as executing in an asynchronous thread

6. Inject configuration file properties

@EnableConfigurationProperties, start the @ConfigurationProperties function
@ConfigurationProperties, automatically inject the content in the properties file into the properties corresponding to the bean
@DeprecatedConfigurationProperty, use it on the getter() method of the configuration file, mark the field as expired, and prompt the replaced field. Generally used for spring-boot-configuration-processor.
@NestedConfigurationProperty, marked on the field of the configuration file, prompts spring-boot-configuration-processor, and the configuration contains nested configurations.
spring-configuration-metadata.json provides configuration meta-information, and there will be syntax prompts when writing properties configuration. Introduce the spring-boot-configuration-processor project in the project, which will scan the @ConfigurationProperties annotation and automatically generate spring-configuration-metadata.json

Seven, Jpa

1、@Entity ,@Table(name=“”)

Indicates that this is an entity class, generally used in jpa, and 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 required to represent the number in the database table. The id is the general attribute of these mapped entity classes. If it is handed over to jpa to uniformly produce the primary key id number, then use a parent class to encapsulate these general attributes and mark them with @MappedSuperClass.

Notice:

  • A class marked @MappedSuperClass will not be a complete entity class, it will not be mapped to a database table, but its attributes are mapped to the database fields of its subclasses.
  • Classes marked with @MappedSuperClass can no longer be marked with @#Entity or @Table annotations, and do not need to implement serialization interfaces.

3、@NoRepositoryBean

Generally used as the repository of the parent class, with this annotation, spring will not instantiate the repository.

4、@Column

Can be omitted if the field and column names are the same.

5、@Id

Indicates that the attribute is the primary key.

6、@Transient

Indicates that the attribute is not a mapping to a field of a database table, and the ORM framework will ignore this attribute.

If an attribute is not a field mapping of a database table, it must be marked as @Transient, otherwise, the ORM framework will annotate it as @Basic by default.

7、@Basic

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

The type supports Java basic types (byte, short, int, long, float, double, char, boolean), wrapper classes, enumeration classes, and types that implement the serializable interface.

The @basic annotation has two attributes:

  • There are two options for fetch to specify the loading mechanism of the attribute
    : EAGER (instant loading, default value) and LAZY (lazy loading). Immediate loading means that the attribute value must be loaded when the object is instantiated, and lazy loading means when the instance The object is not loaded when the object is instantiated, only when the property is called.

  • optional is used to specify whether the attribute is empty.
    There are two options: true (empty, default value) and false.
    If you don’t add @Basic annotation to your entity class, it will automatically add @Basic and use the default value.

8、@JsonIgnore

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

There will be some operation and maintenance fields in the Bean entity. When returning information to the front desk, it is not desirable to return the corresponding values ​​together. At this point, you can add @JsonIgnore to the corresponding property, or you can add the annotation @JsonIgnoreProperties(value="{password}") to the User class

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

8. Import configuration file

1、@PropertySource

Introduce a single properties file:

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

Introduce multiple properties files

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

2. @ImportResource imports the xml configuration file

It can be divided into two modes, classpath for relative path and file for absolute path.

Note: Value or locations may not be written for a single file.

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

@Value("${properties中的键}")
 
private String xxx;

3. @Import imports additional configuration files

Similar to XML configuration, it is used to import configuration classes. You can import configuration classes annotated with @Configuration or implement ImportSelector/ImportBeanDefinitionRegistrar.

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

Nine, business notes

@Transactional

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

hint
The @Transactional annotation can only be applied to methods with public visibility, and can be applied to interface definitions and interface methods. The method will override the transaction declared above the class.

Programmatic transactions:

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

Declarative transactions:

Based on AOP, its essence is to intercept the method before and after, and then create or join a transaction before the target method starts, and submit or roll back the transaction according to the execution status after the target method is executed. Transaction operations can be performed through @Transactional , which is faster and simpler. Recommended Use.

Transaction Propagation Behavior

//If there is currently a transaction, join the transaction; if there is no current transaction, create a new transaction. It's the default value.
@Transactional(propagation = Propagation.REQUIRED)
//Create a new transaction, if there is a transaction, suspend the current transaction
@Transactional(propagation = Propagation.REQUIRES_NEW)
//If there is a transaction, join the transaction; if If there is no transaction currently, continue to run in a non-transactional manner
@Transactional(propagation = Propagation.SUPPORTS)
//Run in a non-transactional manner, if there is a transaction currently, suspend the current transaction.
@Transactional(propagation = Propagation.NOT_SUPPORTED)
//If there is a transaction currently, join the transaction; if there is no transaction, throw an exception.
@Transactional(propagation = Propagation.MANDATORY)
//If there is a transaction currently, create a transaction to run as a nested transaction of the current transaction; if there is no transaction currently, the value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.
@Transactional(propagation = Propagation.NESTED)
//Run in a non-transactional manner, and throw an exception if there is a current transaction.
@Transactional(propagation = Propagation. NEVER)

basic use

1. Add the @EnableTransactionManagement annotation to the startup class to enable springboot transactions
 Add the @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) annotation to the startup class to solve the problem that calling other methods @Transactional () without transactions in the same class
  does not take effect ( ((XXXServiceImpl) AopContext.currentProxy()).save(User);) This annotation can also solve similar annotation problems such as @Async
2. Add transaction annotations to methods

@Transactional(propagation = Propagation.MANDATORY)
public void aa(){
    
    
 
}

Precautions for use (to prevent transaction failure)

1. When a method with @Transactional is called without a @Transactional method, it will cause the failure of the Transactional function
. , there is no dynamic proxy object, so the transaction rollback is invalid.

2. Even if the exception is caught inside the @Transactional method, the transaction will not be rolled back if the exception is not rethrown in the catch code block.
Principle: Look at the source code of spring:
the invokeWithinTransaction method in the TransactionAspectSupport class

3. To annotate non-public methods with transactions, @Transactional will be invalid.
Reason: It should be that when Spring AOP is proxied, the transaction interceptor intercepts before and after the target method, and the intercept method of DynamicAdvisedInterceptor will obtain the transaction configuration information of Transactional annotation, because when Spring AOP is proxied, as shown in the above figure, TransactionInterceptor (transaction
interceptor ) to intercept before and after the execution of the target method, the intercept method of DynamicAdvisedInterceptor (the inner class of CglibAopProxy) or the invoke method of JdkDynamicAopProxy will indirectly call the computeTransactionAttribute method of AbstractFallbackTransactionAttributeSource, which will indirectly call the computeTransactionAttribute method of AbstractFallbackTransactionAttributeSource, This method will get the transaction configuration information of the Transactional annotation. He will first check whether the modifier of the transaction method is public. If it is not public, the attribute configuration information of @Transactional will not be obtained.

4. In a class, the A method is annotated by the transaction, and the B method is also annotated by the transaction.
Phenomenon: An error is reported when executing method B, but the exception is caught by A, and the transaction will also fail at this time.

十、Spring Cloud

1、@EnableEurekaServer

Used on the springboot startup class, indicating that this is an eureka service registry;

2、@EnableDiscoveryClient

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

3、@LoadBalanced

Enable load balancing capability;

4、@EnableCircuitBreaker

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

5、@HystrixCommand(fallbackMethod=”backMethod”)

Used in methods, fallbackMethod specifies the circuit breaker callback method;

6、@EnableConfigServer

Used in the startup class, indicating that this is a configuration center, open the Config Server;

7、@EnableZuulProxy

Turn on zuul routing and use it on the startup class;

8、@SpringCloudApplication

@SpringBootApplication
@EnableDiscovertyClient
@EnableCircuitBreaker
are SpringBoot annotations, registration service center Eureka annotations, and circuit breaker annotations respectively. For SpringCloud, these are the three annotations that each microservice must have, so the @SpringCloudApplication annotation collection is introduced.

9、@ConfigurationProperties

(1) Introduction to @ConfigurationProperties annotation

The ConfigurationProperties annotation is used extensively in the Spring source code. For example, server.port is obtained from this annotation. By using it in conjunction with other annotations, Bean configuration on demand can be realized.

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

(2) Code example

spring.datasource.url=jdbc:mysql://127.0.0.1:8888/test?useUnicode=false&autoReconnect=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
@ConfigurationProperties(prefix = "spring.datasource")
@Component
public class DatasourcePro {
    
    
    private String url;
    private String username;
    private String password;
    // 配置文件中是driver-class-name, 转驼峰命名便可以绑定成
    private String driverClassName;
    private String type;
 
    ...
}

The above code realizes the assignment of properties through configuration files.

(3) Precautions

@ConfigurationProperties and @value have the same function, but @ConfigurationProperties is more convenient to write;
@ConfigurationProperties POJO class naming is stricter, because it must be consistent with the prefix suffix name, otherwise the value will not be bound, special If the suffix name is "driver-class-name" with a horizontal bar, the naming rule in POJO is that the underscore can be changed to camel case, so the binding can be successful, so it is "driverClassName".

The original article is transferred from-Spring Boot common annotations (absolute classic)

Guess you like

Origin blog.csdn.net/qq_27480007/article/details/130384379