Spring Web MVC
Request
@RequestMapping
Provides routing information that is responsible for mapping urls to specific functions in the Controller.
@ GetMapping 👈
GET Request: To GET a specific resource from the server. @requestMapping (value=”/blog”,method= requestMethod.get)
@ PostMapping 👈
POST request: Create a new resource on the server. @postMapping (“/blogs/save”) is equivalent to @requestMapping (value=”/blog/save”,method= requestmethod.post)
The Consumes attribute specifies the request input, and the Produces attribute specifies the request output.
@PostMapping(consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Taco postTaco(@RequestBody Taco taco) {
return tacoRepo.save(taco);
}
Copy the code
@PutMapping
PUT request: Update the resource on the server, and the client provides the updated entire resource.
@DeleteMapping
DELETE request: DELETE a specific resource from the server
@PatchMapping
PATCH request: To update a resource on the server, the client provides the changed properties, which can be seen as a partial update
params
@ PathVariable 👈
Gets the path parameter from the URL template and receives the placeholder value in the request path.
Such as:
@GetMapping("/blog/{id}")
public Result detail(@PathVariable(name = "id") Long id){
Blog blog = blogService.getById(id);
return Result.succ200(blog);
}
Copy the code
@ RequestParam 👈
Retrieve the query parameters and data from the request.
@GetMapping("/blog") // Page processing
public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
Page page = new Page(currentPage,5); IPage pageData =...return Result.succ200(pageData);
}
Copy the code
Here’s the code for the front end:
_this.$axios.get("/blog? currentPage=" + currentPage)
Copy the code
RequestParam supports the following four parameters
- DefaultValue if the request does not carry this parameter, or the parameter is empty, then the defaultValue is enabled
- Name Specifies the name of the binding parameter, which must be the same as that on the URL
- Is the required parameter required
- Value acts as an alias for the name attribute
@ RequestBody 👈
It is used to read the body part of the Request, and its ContentType is data in application/ JSON format. After receiving the data, it will automatically bind the data to the Java object. The system uses HttpMessageConverter(or its own definition) to convert the JSON string in the requested body into a Java object.
@RequiresAuthentication // Authentication is required for access
@PostMapping("/blog/edit")
public Result edit(@Validated @RequestBody Blog blog) {
Blog temp = null;
if(blog.getId() ! =null) {...Copy the code
A request method can only have one @requestBody, but can have multiple @requestParam and @PathVariable.
@ModelAttribute
The @ModelAttribute annotation can be applied to methods or method parameters.
The @ModelAttribute annotation on the method indicates that the method is used 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.
@CrossOrigin
Allow clients from any domain to consume the API
@RestController / / REST controller
@RequestMapping(path="/design",produces="application/json")
@CrossOrigin(origins="*") // Allow cross-domain requests
public class DesignTacoController {
private TacoRepository tacoRepo;
@Autowired
EntityLinks entityLinks;
public DesignTacoController(TacoRepository tacoRepo) {
this.tacoRepo = tacoRepo; }...Copy the code
@Controller
Corresponding to the Spring MVC control layer, it is mainly used to receive user requests and call the functions provided by the Service layer to return data to the front end.
@ RestController 👈
The @RestController annotation is equivalent to the @controller + @responseBody annotation combined.
You don’t need to add @responseBody in front of the method to return json data, but with the @RestController annotation, you can’t return a JSP or HTML page, and the view parser can’t parse a JSP or HTML page.
This annotation fills the return value of the function directly into the HTTP response body and is a REST-style controller.
@ControllerAdvice
Define a global exception handling class. Contains @ Component.
@RestControllerAdvice
@InitBinder
@initBinder is used to annotate a method in @Controller to register a property editor or something for the current Controller, only for the current Controller.
Response
@ResponseStatus
@ResponseStatus(HttpStatus.CREATED)
Copy the code
@ResponseStatus(HttpStatus.UNAUTHORIZED) //401 No permission
@ExceptionHandler(value = ShiroException.class)
public Result handler(ShiroException e){
log.error("No access.");
return Result.succ(401,e.getMessage(),null);
}
Copy the code
@ResponseBody
Indicates that the return result of the method is written directly to the HTTP Response body, which is typically used when fetching data asynchronously to build reST-style apis.
When @requestMapping is used, the return value is usually resolved to the jump path. When @responseBody is added, the return value is not resolved to the jump path and is written directly to the HTTP Response body.
@ExceptionHandler
Declare the exception handling method.
/** * Global exception handling */
@Slf4j
@RestControllerAdvice // @restControllerAdvice is all Controller enhanced to catch exceptions thrown by Spring MVC globally
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.UNAUTHORIZED) //401 No permission
@ExceptionHandler(value = ShiroException.class)
public Result handler(ShiroException e){
log.error("No access.");
return Result.succ(401,e.getMessage(),null);
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = RuntimeException.class)
public Result handler(RuntimeException e){
log.error("Runtime exception");
return Result.succ400(e.getMessage());
}
Copy the code
“Spring Bean”
@ComponentScan
See the Spring Boot section.
@Component
Generic annotations that can annotate any class as a Spring component. This is used when it is difficult to specify which layer a Bean is.
@Service
Corresponding to the service layer, it mainly involves some logic.
@Repository
Corresponds to the persistence layer Dao layer, which is often used for database correlation.
@ Bean 👈
Method level annotations are mostly used in @Configuration or @Component annotated classes
- The @bean annotation applies to methods
- @bean indicates that a method returns a Spring container-managed Bean
- The @bean method name is the same as the returned class name, starting with a lowercase letter
- @Bean is usually used with @Component or @Configuration
- The @bean annotation defaults to the Singleton Scope, which can be set to the prototype Scope via @Scope(” prototype “)
By default, the Bean name is the method name
@Bean
public MyBean myBean(a) {
return new MyBean();
}
Copy the code
The @bean annotation supports setting aliases. Both myBean1 and myBean can be used
@Bean("myBean1")
public MyBean myBean(a) {
return new MyBean();
}
Copy the code
We can use the @bean annotation initMethod and destrodMethod to specify that the Bean needs to call the corresponding methods when it is initialized and destroyed. This is equivalent to the following in the Bean tag of the XML file: The init method and destroy – method – > < bean id = “personService” class = “com. Myapp. Core. Beanscope. PersonService” scope = “singleton” init-method=”init” destroy-method=”cleanUp”>
public class MyBean {
public void init(a) {
System.out.println("MyBean starts to initialize...");
}
public void destroy(a) {
System.out.println("MyBean destroyed...");
}
public String get(a) {
return "MyBean use..."; }}Copy the code
@Bean(initMethod="init", destroyMethod="destroy")
public MyBean myBean(a) {
return new MyBean();
}
Copy the code
@Scope
Declare the scope of a Spring Bean
@Bean
@Scope("singleton")
public User userSingleton(a){
return new User();
}
Copy the code
Here, singleton is actually the default scope for Spring beans.
[Container Configuration]
The @autowired 👈
Automatically import objects into classes. The injected classes are also managed by the Spring container. For example, the Service class is injected into the Controller class.
@Service
public class XxxService{}@Controller
public class xxxController{
@Autowired
private XxxService xxxService;
}
Copy the code
@AutoWired can annotate class member variables, methods, and constructors, and let Spring do the Bean auto-assembly. The default is to match by class, with @qualifier to assemble the bean by the specified name
To identify a class as a Bean class that can be used for @AutoWired annotation auto-assembly, you can decorate the class with @Component, @Repository, @Service, and @Controller annotations.
- @Autowired(Required =true) : When the @autowired annotation is used, the default is @autowired (required=true), indicating that the bean must exist at the time of injection, otherwise the injection will fail.
- @autowired (Required =false) : indicates that the current bean to be injected is ignored. If there is a direct injection, no error will be reported.
- @autowired is on the constructor
First, let’s use @autowired on the constructor. We will see SampleServiceSpring inject it into the AutowireDITestService.
@Component
public class SampleService {
public void sample(a) {
System.out.println("Sample Service"); }}Copy the code
@Component
public class AutowireDITestService {
// ...
private SampleService sampleService;
@Autowired
public AutowireDITestService(SampleService sampleService) {
this.sampleService = sampleService;
}
// ...
}
Copy the code
- Add @autowired to the setter method
In the following example, the setter method ExampleService is called with the instance when the AutowireDITestService is created.
@Component
public class ExampleService {
public void example(a) {
System.out.println("Example Service"); }}Copy the code
@Component
public class AutowireDITestService {
// ...
private ExampleService exampleService;
@Autowired
public void setExampleService(ExampleService exampleService) {
this.exampleService = exampleService;
}
// ...
}
Copy the code
//We can also apply @Autowired on methods with any number of arguments.
@Component
public class AutowireCustomMethodDITestService {
private DemoService demoService;
private ExampleService exampleService;
private SampleService sampleService;
@Autowired
public void initialize(DemoService demoService, ExampleService exampleService, SampleService sampleService) {
this.demoService = demoService;
this.exampleService = exampleService;
this.sampleService = sampleService;
}
// ...
}
Copy the code
- Use @autowired on properties
This way we can avoid autowiring setters and getters for properties.
package com.javabydeveloper.spring.autowire.service;
@Component
public class DemoService {
public void demo(a) {
System.out.println("Demo Service"); }}Copy the code
@Component
public class AutowireDITestService {
// @Autowired on property
@Autowired
private DemoService demoService;
// ...
}
Copy the code
- Starting with 5.0, Spring supports @AutoWired annotation of individual method and constructor parameters. But the only part of the core Spring Framework that actively supports auassemble parameters is JUnit Jupiter support in the Spring-test module.
@SpringJUnitConfig(AppConfigForAutowired.class)
class AutowireParametersTest {
private SampleService sampleService;
// @Autowired on constructor parameters
AutowireParametersTest(@Autowired SampleService sampleService) {
this.sampleService = sampleService;
}
// @Autowired on method parameters
@Test
void injectServicesTest(@Autowired DemoService demoService,
@Autowired(required = true) ExampleService exampleService) { demoService.demo(); exampleService.example(); sampleService.sample(); }}Copy the code
@Primary
When an interface has two different implementation, using the @autowired annotation will be submitted to the org, springframework. Beans. Factory. NoUniqueBeanDefinitionException abnormal information,
Set Primary to BeanDefinition Primary to BeanDefinition Primary to BeanDefinition Primary
@PostConstruct
When we annotate a method in a Spring Bean with the @PostConstruct annotation, it executes after the Spring Bean is initialized.
We can annotate only one method using the @PostConstruct annotation. This annotation is part of the Common Annotations API, which is part of the JDK module javax.annotation- API. Therefore, if you use this annotation in Java 9 or later, you must explicitly add this JAR to your project. If you are using Maven, add the following dependencies to it.
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
Copy the code
If you are using Java 8 or earlier, you do not need to add the above dependencies.
@PreDestroy
When we annotate a Spring Bean method with PreDestroy annotation, it gets called when bean instance is getting removed from the context.
This is a very important point to understand — If your Spring bean scope is “prototype” then it’s not completely managed By the spring container and PreDestroy method won’t get called.
@Qualifier
When there are more than one Bean of the same type, you can specify it using the Qualifier(“name”). Used in conjunction with @AutoWired.
【 Spring Boot 】
Conditional assembly
A new annotation added in Spring 4.0 to identify a Spring Bean or Configuration file. The Configuration is enabled only when specified conditions are met.
Register beans conditionally
- @ConditionalExpression
- @ConditionalOnNotWebApplication
- @ConditionalOnWebApplication
- @ConditionalOnResource
- @ConditionalOnProperty
- @ConditionalOnMissingBean
- @ConditionalOnBean
- @ConditionalOnMissingClass
- @ConditionalOnClass
@SpringBootApplication
@SpringBootApplication
Automatically loads all configuration files and scans for components in the current package and its subpackages.
This is the cornerstone of a SpringBoot project. When a SpringBoot project is created, it is added to the main class by default, identifying it as a SpringBoot application.
It is a combination of @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan
@ComponentScan
Spring 3.1 added annotations to enable component scanning instead of the Component-scan configuration in the configuration file. Automatically scan the @Component annotation in the package path to register the bean instance into the context.
Scan beans annotated by @Component(@Service, @Controller). By default, the annotation scans all classes in the package where the class belongs.
@EnableAutoConfiguration
When this annotation is enabled, SpringBoot can configure Spring beans based on the packages or classes in the current classpath.
@AutoConfigurationPackage
@SpringBootConfiguration
A variant of the @configuration annotation, which is only used to decorate SpringBoot configurations.
@ Configuration 👈
The <Beans> tag @bean is equivalent to the <Beans> tag in Spring’s XML configuration file.
Methods annotated by @Bean in the @Configuration class are enhanced by CGLIB proxying by Spring.
Allows you to register additional beans or import additional configuration classes in the Spring context
To declare a configuration class, you can use the @Component annotation instead. Configuration Indicates two configurations
Full mode: @Configuration(proxyBeanMethods = true) Lite mode: @Configuration(proxyBeanMethods = false) Lightweight mode
[Read configuration information]
@ value ⚙
Read simple configuration information. Let’s say the YML file has car: blah blah blah
@Value("${car}")
String car;
Copy the code
@ ConfigurationProperties ⚙
Used to load additional Configuration (such as.properties files) on the @Configuration annotation class, or on the @Bean annotation method.
@Component: Injected into the container as a Component @ConfigurationProperties: Bound to the configuration file
@ EnableConfigurationProperties ⚙
Must be used in conjunction with the @ConfigurationProperties annotation to enable support for the @ConfigurationProperties annotation configuration Bean.
@ EnableConfigurationProperties: open the specified class attribute configuration function, and injected into the containerBinding to a configuration file is still binding.
[Parameter verification]
The JSR is a set of javabeans parameter validation standards that define a number of commonly used validation annotations that can be added directly to JavaBean properties.
The Hibernate Validator framework is actually used for verification. The Hibernate-Validator package already exists in the Spring-boot-starter – Web dependencies of the SpringBoot project, so there is no need to introduce the dependencies.
When using annotations, the recommended import is:
import javax.validation.constraints.xxxx;
Copy the code
- @notempty The annotated string cannot be null or null
- @notblank The annotated string is not null and must contain a non-whitespace character
- @null The annotated element must be Null
- @notnull The annotated element must not be null
- @AssertTrue The annotated element must be true
- @AssertFalse The annotated element must be false
- @Pattern(regex=,flag=) Annotated elements must conform to the specified regular expression
- @email Elements to be annotated must be in the Email format.
- @min (value) The annotated element must be a number whose value must be greater than or equal to the specified minimum value
- @max (value) The annotated element must be a number whose value must be less than or equal to the specified maximum
- @DecimalMin(value) The annotated element must be a number whose value must be greater than or equal to the specified minimum value
- @DecimalMax(value) The annotated element must be a number whose value must be less than or equal to the specified maximum
- @size (Max =, min=) The Size of the annotated element must be within the specified range
- @Digits (Integer, Fraction) The annotated element must be a number, and its value must be within an acceptable range
- @past The annotated element must be a Past date
- @Future The annotated element must be a Future date
...import javax.validation.constraints.NotBlank;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_blog")
public class Blog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Long userId;
@notblank (message = "title cannot be empty ")
private String title;
@notblank (message = "feed cannot be empty ")
private String description;
@notblank (message = "content cannot be empty ")
private String content;
// The format of the time display in the front end is not satisfactory, add a note
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDateTime created;
private Integer status;
}
Copy the code
【 Spring Cloud 】
@SpringCloudApplication
@EnableDiscoveryClient
@SpringBootApplication
Commonly used with
- @Controller class + @Autowired property (Service class)
- @Configuration class + @Bean method, integrated with other frameworks