springboot: common annotations

springboot: common annotations

1, spring common annotations

Package scanning + Component annotation

@Component: Refers to various components
@Controller,@Service,@Repository Can be called@Component. 
@Controller: Control layer
@Service: Business layer
@Repository: Data access layer

selector

@Conditional,Only when the specified conditions are met can the component be registered
@ConditionalOnBean,appoint bean The current is registered only when in context bean. If it is used on a method, the default dependent class is the return type of the method
@ConditionalOnClass,Specify class in classpath The current is initialized only when bean. If it is used on a method, the default dependent class is the return type of the method
@ConditionalOnCloudPlatform,The configuration is registered only on the specified cloud platform
@ConditionalOnExpression,appoint spel by true Register configuration on
@ConditionalOnJava,In specified java Register configuration on version
@ConditionalOnJndi
@ConditionalOnMissingBean,appoint bean The current is initialized only when it is not in the context bean. If it is used on a method, the default dependent class is the return type of the method
@ConditionalOnMissingClass,The specified class is not present classpath The current is initialized only when bean. If it is used on a method, the default dependent class is the return type of the method
@ConditionalOnNotWebApplication,Not in web Environment only registered configuration
@ConditionalOnProperty,Whether the value in the configuration file is equal to the specified value, and then the configuration is registered
@ConditionalOnResource,appoint resources All in classpath Registered configuration on
@ConditionalOnSingleCandidate,There is only one candidate in the context bean Register configuration only when
@ConditionalOnWebApplication,Yes web Environment only registered configuration

Annotation of injected bean

@Autowired: from spring provide
    1.@Autowired Can act on variables setter Method and constructor
    2.An attribute is required,Can be configured as false

@Resource: from jdk provide 
    
@Primary:Give Way spring For automatic assembly, the preferred one is used by default bean
    
@Autowired It is matched by type by default,@Resource Matches by name,@Autowired Match by name if necessary@Qualifier Use together 

Initialization and destruction methods

@Bean(initMethod="init",destoryMethod="destory")

@PostConstruct: Initialization method;@PreDestory: Destruction method

Java configuration class related annotations

@Configuration:Declare the current class as configuration class
@Bean:Annotation on a method, declaring the return value of the current method as a bean,replace xml Ways in
@ComponentScan:Used for Component Scan    

@Attribute support of Bean

@Scope Annotation is springIoc A scope (method) in the container must have@Bean)
   	Singleton: Single case,One Spring There is only one in the container bean Instance, default mode
    Protetype: Multiple cases, each acquisition Bean There will be a new instance when
    Request: web In the project, give each http request Create a new one bean
    Session: web In the project, give each http request Create a new one bean
    GlobalSession: For everyone global http session Create a new one Bean example
    
@Scope(value="prototype")    

@Value annotation

1.Basic value
    @Value("Zhang San")
	private String name;
2.Read configuration file
    @Value("${person.nickName}")
	private String nickName;
3.write SpEL expression
    @Value("#{20-2}")
	private Integer age;

Enable * * * annotation

@EnableAspectAutoProxy: Open pair AspectJ Support of automatic agent;
@EnableAsync: Enable asynchronous method support;
@EnableScheduling: Enable support for planned tasks;
@EnableWebMvc: open web MVC Configuration support of;
@EnableConfigurationProperties: Open pair@ConfigurationProperties Annotation configuration Bean Support of the;
@EnableJpaRepositories: Open pair SpringData JPA Repository Support of the;
@EnableTransactionManagement: Enable the support of annotated transactions;
@EnableCaching: Enable annotated cache support;

Load profile

@PropertySource

  • Import a single properties file:

    @PropertySource(value = {"classpath:xxxx/xxxx.properties"})
    
  • Introducing multiple properties files

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

@ConfigurationProperties specifies the rules for reading configuration files, such as what the prefix is, whether nonexistent fields can be ignored, etc

@ConfigurationProperties(prefix = "suning.rocketmq")

@Value

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

@Import: the component to import into the container

@Import({Color.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class MainConfig2 {
	@Scope("prototype")
	@Bean("person")
	public Person person() {
		System.out.println("I am Person");
		return new Person("Su xiaonuan",25);
	}
}

2, Spring MVC common annotations

@EnableWebMvc:Open in configuration class Web MVC Configuration support for
@Controller:
@RequestMapping:For mapping web Request, including access path and parameters
@ResponseBody:Support putting the return value into response Inside, rather than a page, the user usually returns json data
@RequestBody:allow request Parameters for request Body, not after the directly connected address
@PathVariable:Used to receive path parameters, such as@RequestMapping("/hello/{name}")The declared path can be obtained by placing the annotation in front of the parameter, usually as Restful Interface implementation method of
@RestController:amount to@Controller and@ResponseBody Combination of
@ControllerAdvice:
	Global exception handling,Global data binding,Global data preprocessing
@ExceptionHandler:Used to handle exceptions in the global controller
    
@ModelAttribute:
	1.Annotation method :If put@ModelAttribute When placed on the annotation of the method, it represents: the Controller All methods of are executed before calling@ModelAttribute method. You can put this@ModelAttribute Properties, applying to BaseController Among them, all Controller inherit BaseController,You can call Controller When, execute first@ModelAttribute method. For example, permission verification (you can also use Interceptor)etc.
	2.Annotate the parameters of a method:When used as a parameter of a method, the indicated parameter should be retrieved from the model. If it does not exist, it should be instantiated first and then added to the model. Once it appears in the model, the parameter field should be populated from all request parameters with matching names

3, Transaction annotation

@When the Transactional annotation is placed at the class level, it means that all public methods of this class are configured with the same transaction attribute information. All methods of EmployeeService support transactions and are read-only. When @ Transactional is configured at the class level and @ Transactional is configured at the method level, the application will manage transactions with the transaction attribute information at the method level. In other words, the transaction attribute information at the method level will overwrite the relevant configuration information at the class level.

@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)
@Service(value ="employeeService")
public class EmployeeService

@Attribute information of Transactional annotation

Attribute nameexplain
nameWhen there are multiple transaction managers in the configuration file, you can use this attribute to specify which transaction manager to select.
propagationTransaction propagation behavior. The default value is REQUIRED.
isolationThe isolation of transactions. The DEFAULT value is DEFAULT.
timeoutThe timeout of the transaction. The default value is - 1. The transaction is rolled back automatically if the time limit is exceeded.
read-onlySpecifies whether the transaction is read-only. The default value is false; To ignore methods that do not require transactions, such as reading data, you can set read only to true.
no-rollback- forThrow the exception type specified by no rollback for and do not roll back the transaction.

4, Timer

@EnableScheduling,Enable scheduled task function
@Scheduled,Execute the method according to the specified execution cycle
@Schedules,Contains multiple@Scheduled,Multiple cycle configurations can be run simultaneously
@EnableAsync,Enable the asynchronous execution of methods through@Async Or customize the annotation to find the method that needs to be executed asynchronously. Through implementation AsyncConfigurer Interfaced getAsyncExecutor()and getAsyncUncaughtExceptionHandler()Method customization Executor And exception handling.
@Async,The marking method is executed in an asynchronous thread

5, Cache

@EnableCaching,Enable cache configuration and support subclass proxy or AspectJ enhance
@CacheConfig,Under one class, public cache configuration is provided
@Cacheable,Put it on the method and class, and cache the return values of all methods under the method or class
@CachePut,Each time, execute the method first, and then put the result into the cache
@CacheEvict,Delete cache
@Caching,Can configure@Cacheable,@CachePut,@CacheEvict

6, Common notes of Jason

@JsonIgnoreProperties

This annotation is a class annotation. It is used to ignore some attributes in Java beans during json serialization. Serialization and deserialization are affected

//Filter the name and age attributes when generating json
@JsonIgnoreProperties({"name"},{"age"})
public class  user {
    private  String name;
    private int age;
}

@JsonIgnore

This annotation is used on properties or methods (preferably properties), and its function is the same as @ JsonIgnoreProperties above

//age attribute is not generated when json is generated
public class user {
    private String name;
    @JsonIgnore
    private int age;
}

@JsonFormat

This annotation is used for attributes or methods (preferably attributes), which can easily convert the Date type directly to the pattern we want

public class User{
    @JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
    private Date date;
}

@Transient

If an attribute is not a field mapping of the database table, it must be marked as @ Transient. Otherwise, the ORM framework defaults to its annotation as @ Basic

@JsonIgnoreType

Marked on a class. When other classes have this class as an attribute, the attribute will be ignored

@JsonProperty

@JsonProperty can specify the name of a property and json mapping. For example, we have a json string with {"user_name": "aaa"},
In java, if the naming should follow the hump rule, it is userName. In this case, specify the mapping rules of the two through the @ JsonProperty annotation. This annotation is also commonly used

public class SomeEntity {
    @JsonProperty("user_name")
    private String userName;
}

@JsonSerialize

This annotation is used on attributes or getter methods to embed our customized code during serialization. For example, when serializing a double, it is limited to two decimal places

@JsonDeserialize

This annotation is used on attributes or setter methods. It is used to embed our customized code during deserialization, similar to @ JsonSerialize above

Keywords: Java Spring Spring Boot

Added by aayatoos on Wed, 23 Feb 2022 07:58:27 +0200