Spring Boot common annotation summary
1. Startup annotation @SpringBootApplication
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
// ... 此处省略源码
}
Looking at the source code, we can find that @SpringBootApplication is a composite annotation, including @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan.
The @SpringBootConfiguration annotation inherits the @Configuration annotation and is mainly used to load configuration files.
@SpringBootConfiguration inherits from @Configuration, and the functions of the two are also consistent. The current class is marked as a configuration class, and one or more declared in the current class will be @Bean The instance of the annotation marked method is included in the spring container, and the instance name is the method name.
@EnableAutoConfiguration annotation, enabling the automatic configuration function
@EnableAutoConfiguration can help SpringBoot applications load all eligible @Configuration configurations into the IoC container created and used by the current SpringBoot. With the help of an original tool class of the Spring framework: the support of SpringFactoriesLoader, @EnableAutoConfiguration can intelligently and automatically configure the function to be successful
The @ComponentScan annotation is mainly used for component scanning and automatic assembly.
The function of @ComponentScan is actually to automatically scan and load qualified components or bean definitions, and finally load these bean definitions into the container. We can specify the scope of @ComponentScan automatic scanning through attributes such as basePackages. If not specified, the default Spring framework implements scanning from the package that declares the class where @ComponentScan is located. By default, it is not specified, so it is best to put the startup class of SpringBoot Under the root package.
2. Controller Relevant annotations
@Controller
controller to process http requests.
@RestController Composite annotation
View @RestController source code
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
From the source code, we know that the @RestController annotation is equivalent to the combined effect of @ResponseBody+@Controller. The effect of RestController is to directly display the object returned by the method in json format on the browser.
@RequestBody
reads Request Body through HttpMessageConverter and deserializes it into an Object (generally referring to) object
@RequestMapping
@RequestMapping is one of the most commonly used annotations in Spring web applications. This annotation will map HTTP requests to the processing methods of MVC and REST controllers
@GetMapping is used to map HTTP get requests to method annotations of specific handlers Annotation
shorthand: @RequestMapping(value = "/say", method = RequestMethod.GET) is equivalent to: @GetMapping(value = "/say")
GetMapping source code
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
//...
}
Is the abbreviation of @RequestMapping(method = RequestMethod.GET)
@PostMapping method annotation for mapping HTTP post requests to specific handlers
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {
//...
}
Is the abbreviation of @RequestMapping(method = RequestMethod.POST)
3. Get the request parameter value
@PathVariable: Get the data in the url
@Controller
@RequestMapping("/User")
public class HelloWorldController {@RequestMapping("/getUser/{uid}")
public String getUser(@PathVariable("uid")Integer id, Model model) {
System.out.println("id:"+id);
return "user";
}
}
Example request: http://localhost:8080/User/getUser/123
@RequestParam: Get the value of the request parameter
@Controller
@RequestMapping(“/User”)
public class HelloWorldController {@RequestMapping("/getUser")
public String getUser(@RequestParam("uid")Integer id, Model model) {
System.out.println("id:"+id);
return "user";
}
}
Example request: http://localhost:8080/User/getUser?uid=123
@RequestHeader Bind the value of the Request header part to the parameter of the method
@CookieValue Bind the value of the cookie in the Request header to the parameter of the method
4. Inject bean-related
@Repository
DAO layer annotations, and the interface in the DAO layer inherits JpaRepository <T, ID extends Serializable>, you need to introduce a jar of related jpa in build.gradle to automatically load.
Repository annotation source code
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";}
@Service
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";
}
@Service is a special case of the @Component annotation. It acts on the class.
The scope of the @Service annotation is a singleton by default
. When using annotation configuration and class path scanning, the class marked by the @Service annotation will be scanned by Spring and registered as a Bean
@Service. To mark the service layer component, it means to define a bean
@Service without passing parameters when using it. The bean name defaults to the class name of the current class, and the first letter is lowercase
when @Service("serviceBeanId") or @Service(value="serviceBeanId") is used Pass parameters, use value as the bean name
@Scope scope annotation
@Scope acts on the class and method to configure the scope of the spring bean, which identifies the scope of the bean
@Scope source code
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {/**
* Alias for {@link #scopeName}.
* @see #scopeName
*/
@AliasFor("scopeName")
String value() default "";@AliasFor("value")
String scopeName() default "";ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
Property introduction
The value
singleton indicates that the bean is a singleton. (Default)
prototype indicates that the bean is multi-instance, that is, a new object will be created every time the bean is used.
request In an http request, one bean corresponds to one instance.
session In an httpSession, a bean corresponds to an instance.
proxyMode
DEFAULT Do not use a proxy. (Default)
NO Do not use proxy, equivalent to DEFAULT.
INTERFACES uses an interface-based proxy (jdk dynamic proxy).
TARGET_CLASS uses a class-based proxy (cglib).
@Entity entity class annotation
@Table(name = "database table name"), this annotation is also annotated on the entity class, corresponding to the corresponding table in the database.
The @Id and @Column annotations are used to mark the fields in the entity class, the pk field is marked as @Id, and the rest are @Column.
@Bean generates a bean method
@Bean clearly indicates a method, generates a bean method, and hands it over to the Spring container for management. Support for aliases @Bean("xx-name")
@Autowired automatically imports
the @Autowired annotation to act on constructors, methods, method parameters, class fields, and annotations. The
@Autowired annotation can realize the automatic injection of beans.
@Component
instantiates ordinary pojos into the spring container, which is equivalent to the configuration file.
Although with @Autowired, we still have to write a bunch of bean configuration files, which is quite troublesome, and @Component tells spring that I am a pojo class, register me in the container, and spring will automatically extract relevant information. Then we don't have to write troublesome xml configuration files
5. Import configuration file
@PropertySource annotation
Introduce a single properties file:
@PropertySource(value = {“classpath : xxxx/xxx.properties”})
Introduce multiple properties files:
@PropertySource(value = {“classpath : xxxx/xxx.properties”,“classpath : xxxx.properties”})
@ImportResource import xml configuration file
can be divided into two modes: relative path classpath, absolute path (real path) file
Note: A single file does not need to write value or locations, both value and locations are available
relative path (classpath)
Introduce a single xml configuration file: @ImportSource("classpath: xxx/xxxx.xml")
Introduce multiple xml configuration files: @ImportSource(locations={“classpath: xxxx.xml”, “classpath: yyyy.xml”})
absolute path (file)
Import a single xml configuration file: @ImportSource(locations= {“file : d:/hellxz/dubbo.xml”})
Introduce multiple xml configuration files: @ImportSource(locations= {“file : d:/hellxz/application.xml”, “file : d:/hellxz/dubbo.xml”})
Value: Use the @Value annotation to get the value in the configuration file
@Value("Key in ${properties}")
private String xxx;
@Import Import additional configuration information
The function is similar to XML configuration, used to import configuration classes, you can import configuration classes with @Configuration annotations or implement ImportSelector/ImportBeanDefinitionRegistrar.
Example of use
@SpringBootApplication
@Import({SmsConfig.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6. Transaction annotation @Transactional
In Spring, there are two ways to implement transactions, namely programmatic transaction management and declarative transaction management.
Programmatic transaction management: Programmatic transaction management uses TransactionTemplate or directly uses the underlying PlatformTransactionManager. For programmatic transaction management, spring recommends using TransactionTemplate.
Declarative transaction management: built on top of 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. Recommend to use
7. Global exception handling
@ControllerAdvice Unified exception handling
@ControllerAdvice annotation defines global exception handling class
@ControllerAdvice
public class GlobalExceptionHandler {
}
The @ExceptionHandler annotation declares exception handling methods
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)
@ResponseBody
String handleException(){
return "Exception Deal!";
}
}