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 { // ... Omitted source code}Copy the code

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

The @springBootConfiguration annotation, inherited from the @Configuration annotation, is mainly used to load Configuration files

@SpringBootConfiguration inherits from @Configuration and has the same functionality, marking the current class as a Configuration class and incorporating into the Spring container one or more instances of methods declared in the current class marked with the @Bean annotation, and instance names being method names.

@enableAutoConfiguration Indicates that the automatic configuration function is enabled

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

@ComponentScan annotation, mainly used for component scanning and automatic assembly

@ComponentScan automatically scans and loads qualified component or bean definitions, and eventually loads those 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 {

    /**
     * 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, ifAny (or empty String otherwise) * @since 4.0.1 */ @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

  • @requestheader binds the values of the Request header to the method parameters

  • The @cookievalue binds the cookie value of the Request header to the method’s parameters

Inject bean correlation

@Repository

The DAO layer annotation, which inherits the JpaRepository interface, requires a JAR auto-loading of the associated JPA in build.gradle.

Repository annotated source

@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 "";

}Copy the code

@Service

@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { /** *  The value may indicate a suggestionfor 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 "";
}Copy the code
  • @service is a special case of the @Component annotation that applies to classes

  • 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 beans

  • @service is used to annotate Service layer components to define a bean

  • @service is used with no arguments, and the Bean name defaults to the class name of the current class, starting with a lowercase letter

  • @service (” serviceBeanId “) or @service (value= “serviceBeanId”) uses time-passing arguments, using value as the Bean name

@scope Scope annotation

@scope works 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 {

    /**
     * Alias for {@link #scopeName}.
     * @see #scopeName
     */
    @AliasFor("scopeName")
    String value() default "";

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

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}Copy the code

Attribute is introduced

The value Singleton indicates that the bean is singleton. Prototype indicates that the bean is multi-instance, 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. (DEFAULT) NO does not use a proxy, equivalent to DEFAULT. INTERFACES use an interface-based proxy (JDK Dynamic Proxy). TARGET_CLASS uses a class-based proxy (Cglib).Copy the code

@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

Instantiating a normal POJO into a Spring container is equivalent to a 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"})Copy the code

Introduce multiple properties files:

@PropertySource(value = {"classpath : xxxx/xxx.properties"."classpath : xxxx.properties"})Copy the code

@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("Key} in ${properties")
private String xxx;Copy the code

@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 {}Copy the code

The @ExceptionHandler annotation declares the exception handling method

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException() {return "Exception Deal!"; }}Copy the code

Eight, data

Java architect information



Pick up: https://jq.qq.com/?_wv=1027&k=JEuO2lMC