My official account:
MarkerHub, Java Website:
https://markerhub.com

For more selected articles, please click: Java notebook.md

Small Hub Guide:

SpringBoot has a number of annotations, all to review the familiar ah!


  • Author: Yun Tian
  • Link: https://www.cnblogs.com/tqlin…

Start the @SpringBootApplication annotation

@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 {
    
}

@SpringBootApplication is a composite annotation, including @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan ‘annotation

The @SpringBootConfiguration annotation inherits the @Configuration annotation, which is used to load Configuration files. The @SpringBootConfiguration annotation inherits from the @Configuration annotation. The @SpringBootConfiguration annotation also has the same function, indicating that the current class is a Configuration class. Instance of one or more methods labeled with the @Bean annotation declared in the current class is brought into the Spring container, and the instance name is the method name.

@ EnableAutoConfiguration annotations, Enabling the @EnableAutoConfiguration feature helps SpringBoot applications load all qualified @Configuration configurations into the IOC container that SpringBoot is currently creating and using. The @EnableAutoConfiguration can be intelligently auto-configured with the help of SpringFactOriesLoader, a tool class that is already part of the Spring Framework

The @ComponentScan annotation is used for component scanning and autowiring. The @ComponentScan annotation is used for component scanning and autowiring. The @ComponentScan annotation is used for component scanning and autowiring. We can specify the scope of @ComponentScan automatic scan via properties such as BasePackages. If not specified, the default Spring Framework implementation scans from the package of the class in which @ComponentScan is declared. By default, this is not specified. Therefore, SpringBoot’s startup classes are best placed under the Root Package.

2. Controller related annotations

@Controller

Controller that handles HTTP requests.

@RestController composite annotations

Look at the @RestController source code

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

    
    @AliasFor(annotation = Controller.class)
    String value() default "";
}

As we know from the source code, the @RESTController annotation is the @ResponseBody+@Controller combined. The RESTController uses the effect of displaying the object returned by the method in JSON format directly on the browser.

@RequestBody

Read the Request Body through HttpMessageConverter and deserialize it into an Object Object

@RequestMapping

@RequestMapping is one of the most commonly used annotations in Spring Web applications. This annotation maps the HTTP request to the MVC and REST controller’s processing methods

@GetMapping Method annotations used to map HTTP GET requests to a specific handler

@requestMapping (value = “/say”,method = requestMethod.get) @getMapping (value = “/say”)

GetMapping source

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {

}

Is short for @RequestMapping(method = RequestMethod.get)

@PostMapping Method annotations for mapping HTTP POST requests to a specific handler

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = RequestMethod.POST)  public @interface PostMapping { }

Is short for @RequestMapping(method = RequestMethod.post)

3, take the request parameter value

@pathVariable: Gets 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";
    }
}

Sample request: http://localhost:8080/User/getUser/123

@RequestParam: Gets 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"; }}

Sample request: http://localhost:8080/User/getUser? uid=123

IV. Injecting Beans

The DAO layer extends Serializable>. The DAO layer extends Serializable>. The DAO layer extends Serializable> to a database that extends JPA from build.gradle.

Repository annotation source

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

    
    @AliasFor(annotation = Component.class)
    String value() default "";

}

@Service
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

    
    @AliasFor(annotation = Component.class)
    String value() default "";
}

The @Service annotation is a special case of the @Component annotation that applies to classes. By default, the @Service annotation is scoped to a singleton using annotation configuration and classpath scanning. The class annotated by @Service annotation will be scanned by Spring and registered as Bean@Service to annotate the Service layer component. This means that the definition of a Bean@Service is used without passing parameters, and the Bean name will default to the class name of the current class. @service (” serviceBeanID “) or @service (value= “serviceBeanID”) is used when passing parameters, The @Scope annotation, applied on classes and methods, is used to configure the Scope of Spring beans. It identifies the Scope of the Bean

@ Scope source

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

    
    @AliasFor("scopeName")
    String value() default "";

    @AliasFor("value")
    String scopeName() default "";

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}

Attribute is introduced

value

  • A singleton indicates that the bean is singleton. (the default)
  • Prototype indicates that the bean is multicase, meaning that a new object is created each time the bean is used.
  • Request In an HTTP request, one bean corresponds to one instance.
  • Session In an HttpSession, one bean corresponds to one instance.

proxyMode

  • Default does not use a proxy. (the default)
  • No does not use a proxy and is equivalent to DEFAULT.
  • Interfaces use interface-based proxies (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 for the corresponding Table in the database.

The @ID and @Column annotations are used to annotate the fields in the entity class, the PK fields are annotated as @ID, and the other @Column annotations.

@Bean generates a method for a Bean

@Bean explicitly indicates a way to generate a Bean and give it to the Spring container to manage. Support for alias @bean (“xx-name”)

@Autowired is automatically imported

The @Autowired annotation is applied to constructors, methods, method parameters, class fields, and annotations

The @Autowired annotation enables automatic injection of beans

The @Component instantiates a regular POJO into the Spring container, which is equivalent to a configuration file

With @Autowired, we still have to write a bunch of bean configuration files, which is quite cumbersome, and @Component tells Spring that I am a POJO class, register me in the container, and Spring will automatically extract the relevant information. Then we don’t have to write a cumbersome XML configuration file

5. Import configuration files

@ PropertySource annotations

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 Imports the XML configuration file

It can be divided into two modes: relative path classpath and absolute path (real path) file

Note: a single file can not write value or locations, value and locations can be used

Relative path (CLASSPATH)

Import a single XML configuration file: @importSource (“classpath: XXX/xxx.xml”)

Import multiple XML configuration files: @importSource (locations={“classpath: xxx.xml”, “classpath: yyyy.xml”})

Absolute path (FILE)

Import a single XML configuration file: @importSource (locations= {“file: d:/hellxz/dubbo.xml”})

Introducing multiple XML configuration files: @ ImportSource (locations = {” XML file: d: / hellxz/application. “, “XML file: d: / hellxz dubbo.”})

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

@value (“${properties}”) private String XXX;

@import imports additional configuration information

Function similar to the XML Configuration, which is used to import the Configuration class that can be imported with @ Configuration annotation Configuration class or implements ImportSelector/ImportBeanDefinitionRegistrar.

Use the sample

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

Transactional annotation @Transactional

In Spring, transactions are implemented in two ways: programmatic transaction management and declarative transaction management

Programmatic transaction management: programmatic transaction management using PlatformTransactionManager TransactionTemplate or directly use the bottom. For programmatic transaction management, Spring recommends using TransactionTemplate. Declarative transaction management: Built on top of AOP. The nature of the transaction is to intercept methods before and after the target method starts, create or join a transaction before the target method starts, commit or roll back the transaction after executing the target method. Transactional actions can be carried out using @Transactional, a faster and simpler method. It is recommended to use

Global exception handling

  • @ControllerAdvice handles exceptions uniformly
  • The @ControllerAdvice annotation defines the global exception handling class
@ControllerAdvice public class GlobalExceptionHandler {} @ExceptionHandler annotation declares the exception handling method @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody String handleException(){ return "Exception Deal!" ; }}

(after)

Recommended reading

Java note daq.md

Amazing, this Java website, everything! https://markerhub.com

The B station of the UP Lord, the JAVA is really good!