Categories
Uncategorized

Spring Boot common comment summary

Spring Boot common comment summary

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, consistent both functions are denoted by the current class is the class configuration, and the current will be within a class declaration of example one or more annotation markers methods @Bean spring into the container, and the instance name is the method name.

@EnableAutoConfiguration notes, open the automatic configuration

@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 components

@ComponentScan function is actually automatically scan and load the assembly qualified or bean definitions, which ultimately will be loaded into a container bean definitions. 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 {

    /**
     * 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)
     * @since 4.0.1
     */
    @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

@RequestHeader the value Request header portion of the request parameters of the method bound to the

@CookieValue the Request header in cookie values ​​for binding to the parameter method

Fourth, related to inject bean

@Repository

DAO layer annotation, DAO layer interface inheritance JpaRepository , 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 {

    /**
     * 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 "";

}

@Service

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

    /**
     * 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 "";
}

    @Service @Component annotation is a special case, in class on the role of

    @Service comment singleton scope by default

    When using annotation configuration and class path scanning, the marked @Service annotation class will be scanned and registered as a Spring Bean

    @Service service layer component used for labeling, denotes a bean definition

    @Service did not pass when using parameters, Bean name defaults to the class name of the current class, the first letter lowercase

    @Service pass parameters ( “serviceBeanId”) or @Service (value = “serviceBeanId”) use, use value as Bean name

@Scope scope notes

@Scope acting on the upper classes and methods used 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 {

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

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

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}

Introduction property

value
    singleton   表示该bean是单例的。(默认)
    prototype   表示该bean是多例的,即每次使用该bean时都会新建一个对象。
    request     在一次http请求中,一个bean对应一个实例。
    session     在一个httpSession中,一个bean对应一个实例。
    
proxyMode
    DEFAULT         不使用代理。(默认)
    NO              不使用代理,等价于DEFAULT。
    INTERFACES      使用基于接口的代理(jdk dynamic proxy)。
    TARGET_CLASS    使用基于类的代理(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 general 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 a plurality 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中的键}”)
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!";
    }
}

Eight, information

    Java collection problems

    Original Address

Leave a Reply