Spring Boot common principles and organize notes

 

First, start the comment @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 {

    

}

 

View source can be found, @ SpringBootApplication is a complex annotation, it contains @ SpringBootConfiguration, @ EnableAutoConfiguration`, @ ComponentScan` three notes

`` @SpringBootConfiguration notes, inheritance @Configuration notes, primarily used to load configuration file @SpringBootConfiguration inherited from @ Configuration`, the two functions are consistent with the current class is marked class configuration, and will be declared within the current class of one or more examples of the method to mark annotated @Bean spring into the container, and the instance name is the name of the method.

@EnableAutoConfiguration notes, open the automatic configuration capabilities @EnableAutoConfiguration can help SpringBoot apply to all eligible @Configuration configuration is loaded into the current SpringBoot create and use IoC container. With Spring Framework is a tool of the original class: the support SpringFactoriesLoader, @ EnableAutoConfiguration can intelligently auto-configure the effect was able to be accomplished

@ComponentScan annotation, mainly for scanning and automatic assembly @ComponentScan components function in fact automatically scans and loading assembly qualified or bean definitions, these bean definitions ultimately will be loaded into the container. We can attribute specifies the scope of basePackages @ComponentScan automatic scanning, etc., if not specified, the default scan from the Spring framework to achieve the class declaration @ComponentScan package is located, by default, is not specified, it is best to start classes put SpringBoot in the root package.

Two, Controller-related notes

@Controller

Controllers, processing http request.

@RestController complex notes

View @RestController source

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Controller

@ResponseBody

public @interface RestController {

 

    

    @AliasFor(annotation = Controller.class)

    String value() default "";

}

 

We know from source, @ RestController annotation is equivalent to @ ResponseBody + @ Controller together and effects RestController using the method returns the object directly into the json format display in the browser.

@RequestBody

And deserialize Object (refers to) the object by reading the Request Body HttpMessageConverter

@RequestMapping

@RequestMapping is one comment Spring Web applications most frequently used. This annotation will be mapped to HTTP request processing method and MVC controller REST

@GetMapping method for HTTP get request mapped to a particular annotation handler

Shorthand annotation: @RequestMapping (value = "/ say", method = RequestMethod.GET) is equivalent to: @GetMapping (value = "/ say")

GetMapping source

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@RequestMapping(method = RequestMethod.GET)

public @interface GetMapping {

 

}

 

Is an abbreviation @RequestMapping (method = RequestMethod.GET) of

@PostMapping method for HTTP post request is mapped to a particular annotation handler

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@RequestMapping(method = RequestMethod.POST)

public @interface PostMapping {

    

}

 

Is an abbreviation @RequestMapping (method = RequestMethod.POST) of

Third, the fetch request parameter values

@PathVariable: acquiring 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";

    }

}

 

Request Example: http: // localhost: 8080 / User / getUser / 123

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

}

}

 

Request example: http: // localhost:? 8080 / User / getUser uid = 123

Fourth, related to inject bean

@RepositoryDAO annotation layer, DAO layer interface inheritance JpaRepository <T, ID extends Serializable>, needs to be introduced in the relevant jpa build.gradle automatically loaded in a jar.

Notes Source Repository

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

}

 

@Service @Component annotation is a special case, acting on the scope default annotation class @Service single embodiment of the annotation configuration and class path scanning, the marked classes are @Service annotation Spring is scanned and registered by Bean @ Service when to mark the service layer components, means that the definition did not pass a parameter when using the bean @ service, bean name defaults to the class name of the current class, the first letter lowercase @Service ( "serviceBeanId") or @Service (value = "serviceBeanId") use transmission parameters, using the name value bean @Scope scope @Scope annotation functions as in the upper class and method to configure the spring bean scope that 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;

}

 

Introduction property

value

This bean is singleton indicates a single embodiment. (default)

This represents a prototype embodiment is a multi-bean, i.e., each time when the bean will create a new object.

http request in a request, corresponding to an example of a bean.

In one httpSession the session, corresponding to one example of a bean.

proxyMode

DEFAULT does not use a proxy. (default)

NO agent is not used, it is equivalent to DEFAULT.

INTERFACES based agent (jdk dynamic proxy) interface.

TARGET_CLASS using class-based agent (cglib).

@Entity entity class notes

@Table (name = "database table"), the annotation on annotation also entity class corresponding to a respective database tables.

@ Id, @ Column annotation is used to designate the entity class field, pk field labeled @Id, remaining @Column.

A method of generating a bean @Bean

@Bean explicitly indicate a process, a method for producing the bean, and to the Spring container. Support Alias ​​@Bean ( "xx-name")

@Autowired automatically import

@Autowired annotation acts on the constructor, process, process parameters, and the class field annotations

@Autowired Annotations can be automatically injected into the Bean

@Component the ordinary spring pojo instantiated into the vessel, corresponding to the configuration file

Although there has been @Autowired, but we still want to write a bunch of bean configuration files, cumbersome, and @Component is to tell spring, I was pojo class, I registered to the container it, spring will automatically extract the relevant information. So we do not bother to write xml configuration files

V. Import Profiles

@PropertySource comment

The introduction of a single properties file:

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

The introduction of multiple properties files:

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

@ImportResource import xml configuration file

Additional models can be divided into two relative path classpath, an absolute path (true path) file

Note: Single files can not write value or locations, value and locations are available

Relative path (CLASSPATH)

Introducing single xml configuration file: @ImportSource ( "classpath: xxx / xxxx.xml")

Introducing multiple xml configuration file: @ImportSource (locations = { "classpath: xxxx.xml", "classpath: yyyy.xml"})

Absolute path (file)

Introducing single xml configuration file: @ImportSource (locations = { "file: d: /hellxz/dubbo.xml"})

Introducing a plurality xml configuration file: @ImportSource (locations = { "file: d: /hellxz/application.xml", "file: d: /hellxz/dubbo.xml"})

Value: The value used to take notes @Value profile

@Value ( "$ {properties in key}") private String xxx;

@Import import additional configuration information

XML functionally similar configuration to import configuration class, the configuration can be introduced with @Configuration annotation or class implements ImportSelector / ImportBeanDefinitionRegistrar.

Examples of Use

@SpringBootApplication

@Import({SmsConfig.class})

public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);

    }

}

 

Sixth, the transaction comment @Transactional

In Spring, the transaction implemented in two ways, namely programmatic transaction management and declarative transaction management in two ways

Programmatic transaction management: programmatic transaction management TransactionTemplate use or used directly underlying PlatformTransactionManager. For programmatic transaction management, spring recommended TransactionTemplate. Declarative transaction management: built on AOP. Its essence is to intercept method before and after, and then create or join a transaction before the target method begins, commit or roll back the transaction, the transaction can be carried out in accordance with the implementation of the operation by @Transactional after executing the target method, more efficient and simple. Recommended Use

Seven global exception handler

@ControllerAdvice unified exception handling

@ControllerAdvice annotation defines global exception handler class

@ControllerAdvice

public class GlobalExceptionHandler {

}

@ExceptionHandler statement notes exception handling

@ControllerAdvice

public class GlobalExceptionHandler {

 

    @ExceptionHandler(Exception.class)

    @ResponseBody

    String handleException(){

        return "Exception Deal!";

    }

}

 

 

Guess you like

Origin www.cnblogs.com/dgwblog/p/11967375.html