My official account: MarkerHub, Java website: Markerhub.com

For more selected articles, please click: Java Notes Complete.md

Small Hub read:

Springboot notes a lot of, all to review familiar with ha!


  • Author: Yuntian
  • Link: www.cnblogs.com/tqlin/p/116…

Start the 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 {
    
}


Copy the code

View the source code can be found, @SpringBootApplication is a composite annotation, including @SpringBootConfiguration, @EnableAutoConfiguration ‘, @ComponentScan ‘these three annotations

@springBootConfiguration inherits @Configuration, which is used to load Configuration files. @springBootConfiguration inherits @Configuration from @Configuration. One or more instances of methods marked with the @Bean annotation declared in the current class are incorporated into the Spring container, and the instance name is the method name.

@ EnableAutoConfiguration annotations, Enabling @enableAutoConfiguration helps SpringBoot applications load all qualified @Configuration configurations into the IoC container created and used by the current SpringBoot application. With the support of SpringFactoriesLoader, a native tool class of the Spring framework, @enableAutoConfiguration can be automatically configured

The @ComponentScan annotation is used to automatically scan and load qualified component or bean definitions, and eventually load these bean definitions into the container. We can specify the scope for @ComponentScan to be automatically scanned using properties such as basePackages. If not, the default Spring framework implementation scans from the package that declares @ComponentScan. By default, this is not specified. So SpringBoot boot classes are best placed under the root package.

2. Controller related notes

@Controller

Controller, which handles HTTP requests.

@restController composite annotation

Check out the @restController source code

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

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


Copy the code

As we know from the source, the @RestController annotation is equivalent to @responseBody +@Controller combined, and the RestController uses the effect of displaying the object returned by the method directly in json format on the browser.

@RequestBody

Read the Request Body via HttpMessageConverter and deserialize it into an 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 handling methods

@getMapping method annotation 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 {

}


Copy the code

RequestMapping(method = requestMethod.get

@postMapping Method annotation used to map HTTP POST requests to a specific handler

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

RequestMapping(method = requestMethod.post

Third, take 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";
    }
}


Copy the code

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"; }}Copy the code

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

Inject bean correlation

@repository DAO layer annotation, the DAO layer interface inherits JpaRepository<T,ID extends Serializable> and requires a JAR auto-loading associated with JPA in build.gradle.

Repository annotated source

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

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

}


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

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


Copy the code

@service is a special case of the @Component annotation. The @service annotation scope is singleton by default when using annotation configuration and classpath scanning. Classes annotated by the @service annotation are scanned by Spring and registered as bean@service for annotating Service layer components. This means that a bean@service is used with no parameters. The Bean name defaults to the class name of the current class. The first letter is lowercase @service (” serviceBeanId “) or @service (value= “serviceBeanId”). The @scope annotation is used on classes and methods to configure the Scope of the Spring Bean. 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;
}


Copy the code

Attribute is introduced

value

  • The Singleton indicates that the bean is singleton. (the default)

  • Prototype indicates that the bean is multi-case, meaning that an 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 proxies. (the default)

  • NO does not use a proxy, which is equivalent to DEFAULT.

  • INTERFACES use 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 also comments the corresponding Table in the database on the entity class.

The @ID and @column annotations are used to annotate fields in the entity class, with the PK field annotated as @ID and the rest as @column.

@bean A method that generates a Bean

The @bean explicitly indicates a method that generates a Bean and is handed over to the Spring container to manage. Support for alias @bean (“xx-name”)

@autoWired Automatically imports

The @autoWired annotation applies to constructors, methods, method parameters, class fields, and annotations

The @AutoWired annotation enables automatic injection of beans

@Component instantiates ordinary POJos into the Spring container, as in the configuration file

Even with @autowired, we still have to write a bunch of bean configuration files, which is pretty cumbersome, and @Component just tells Spring THAT I’m a POJO class, register me with the container, and Spring will automatically extract that information. Then we don’t have to write the cumbersome XML configuration file

5. Import the configuration file

@ 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 an XML configuration file

There are two additional modes: relative path classpath and absolute path (real path) file

Note: A single file can not write value or locations, but both value and locations can be used

Relative path (classpath)

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

Locations ={” CLASspath: XXXX.xml “, “classpath: YYYY.xml “})

Absolute path (file)

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

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

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

@value (“${properties in key}”) 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); }}Copy the code

Transactional annotation @Transactional

In Spring, transactions are implemented in two ways: programmatic 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 AOP. Its essence is to intercept method before and after and before the start of the target method to create or join a transaction, the execution of the target method according to the execution situation after commit or rollback transaction through @ Transactional affairs operation, could be more efficient and simple. It is recommended to use

7. Global exception handling

  • @controllerAdvice Handle exceptions uniformly

  • The @controllerAdvice annotation defines the global exception handling class

@ControllerAdvice Public Class GlobalExceptionHandler {} @ExceptionHandler Specifies the exception handling method. @ControllerAdvice Public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody String handleException(){ return "Exception Deal!" ; }}Copy the code

(after)

Recommended reading

Java Notes Complete.md

Great, this Java site, everything! https://markerhub.com

The UP master of this B station, speaks Java really good!