This is the sixth day of my participation in Gwen Challenge

1. @Component@BeanWhat is the difference between?

  1. Different objects:@ComponentAnnotations apply to classes, and@BeanAnnotations apply to methods,
  2. @ComponentAutomatic detection and automatic assembly are usually done by path scanningSpringIn the container (we can use@ComponentScanThe annotation defines the path to scan to find the class that identifies the assembly to be automatically assembled toSpringbeanIn the container).@BeanAnnotations are usually the ones we define in the method marked with the annotations that produce thisbean.@BeanTell theSpringThis is an instance of some class, and we’ll give it back to me when we need it.
  3. @BeanAnnotations than@ComponentAnnotations are more customizable, and there are many places we can only pass@BeanAnnotations to registerbean. For example, when we reference a third party library class that needs to be assembled intoSpringContainers can only be passed through@BeanTo implement.

Example use of @bean annotations:

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService(a) {
        return newTransferServiceImpl(); }}Copy the code

Example use of the @component annotation:

@Component
public class ServiceImpl implements AService {... }Copy the code

The following example cannot be implemented with @Component:

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return newserviceImpl3(); }}Copy the code

2. Autowire@ResourceThe difference between

  1. @Autowire@ResourceBoth can be used to assemble beans, and both can be used for fields or setter methods.
  2. @AutowireThe defaultAccording to the typeBy default, the dependent object must exist. If you want to allow null, you can set its required property to false.
  3. @ResourceThe default assembly is by name and by type when no bean matching the name can be found. The name can be specified by the name attribute. If the name attribute is not specified, the annotation defaults to the field name when written to the field, and the annotation defaults to the property name when written to setter methods for assembly.

Note: If the name attribute is specified, it will only be assembled by name.

  • @autowire and @Qualifier combine to have the same effect as @resource:

    @Autowired(required = false) @Qualifier("example")
    private Example example;
    
    @Resource(name = "example")
    private Example example;
    Copy the code
  • @resource Assembly sequence

  1. If both name and type are specified, a unique matching bean assembly is searched from the container and an exception is thrown if none is found.
  2. If the name attribute is specified, an exception is thrown if the assembly of beans whose names match is not found in the container.
  3. If the type attribute is specified, an assembly of beans of a unique type is searched from the container and thrown exceptions are not found or multiple exceptions are found;
  4. If this parameter is not specified, the device is automatically assembled in byName mode. If no match is found, a primitive type is rolled back for matching. If a match is found, the device is automatically assembled.

3. What are the annotations that declare a class as a Spring bean?

  • @Component: generic annotation that can mark any class asSpringThe component. This can be used if a Bean does not know which layer it belongs to@ComponentAnnotation annotation.
  • @Repository: Corresponds to the Dao layer, which is mainly used for database operations.
  • @Service: Corresponding to the service layer, mainly design some complex logic, need to use the Dao layer.
  • @Controller: Corresponds to the Spring MVC control layer, which is mainly used to accept user requests and call the Service layer to return data to the front-end page.
  • @Configuration: Declares this class as a configuration class. You can declare one or more classes in this class@BeanMethods.

4. @Configuration: Configure class annotations

@Configuration indicates that one or more @bean methods can be declared in a class and can be handled by the Spring container to generate Bean definitions and service requests for these beans at run time, for example:

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean(a) {
        // instantiate, configure and return bean ...}}Copy the code

We can register by AnnotationConfigApplicationContext @ the Configuration class:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean = ctx.getBean(MyBean.class);
// use myBean ...
Copy the code

It can also be loaded through Component scanning. @Configuration uses @Component to annotate. Therefore, the @Configuration class can also be scanned by components (especially the
element using XML). The @Configuration class can not only bootstrap with component scanning, but also configure component scanning itself using the @ComponentScan annotation:

@Configuration
@ComponentScan("com.acme.app.services")
public class AppConfig {
    // various @Bean definitions ...
}
Copy the code

Constraints for using @Configuration:

  • Configuration classes must be provided as classes (for example, not as instances returned by factory methods).
  • Configuration classes must be non-final.
  • Configuration classes must be non-native (that is, may not be declared in methods), native annotated methods.
  • Any nested configuration classes must be declared asstatic.
  • @BeanMethod may not in turn create more configuration classes.

In addition to using @Configuration annotations alone, we can also use external beans or annotations, such as the Environment API, @propertysource, @Value, @Profile, etc., which we won’t go into here. For more information, see the documentation for Spring@Configuration.

5. @ControllerAdvice: Handles global exceptions

In Spring 3.2, the @ControllerAdvice, @RestControllerAdvice, @RestController annotations were added, Can be used to define @ExceptionHandler, @initBinder, @ModelAttribute, And apply it to all Controller layer annotations like @requestMapping, @postMapping, @getMapping, etc.

By default, the methods in @ControllerAdvice apply to all controllers across the board. Annotations (), basePackageClasses(), and basePackages() (or its alias value()) are used to define a smaller subset of target controllers. If multiple selectors are declared, the OR logic is applied, which means that the selected controller should match at least one selector. Note that selector checking is performed at run time, so adding many selectors can negatively impact performance and add complexity.

@ControllerAdvice We most often use this in combination with @ExceptionHandler for global exception handling. With the following example, we can catch custom exceptions for handling, and we can customize the status code return:

@ControllerAdvice("com.developlee.errorhandle")
public class MyExceptionHandler {
    /** * Catch CustomException *@param e
     * @returnJson format */
    @ResponseBody
    @ExceptionHandler({CustomException.class}) // Specify the type of exception to intercept
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // Customize the browser return status code
    public Map<String, Object> customExceptionHandler(CustomException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        returnmap; }}Copy the code

See the official documentation for Spring @ControllerAdvice for more information.

6. @Component.@Repository.@ServiceThe difference between

annotations meaning
@Component The most common components can be injected into the Spring container for management
@Repository On the persistence layer
@Service Acts on the business logic layer
@Controller Acting on the presentation layer (Spring-MVC annotations)

@Component is a generic Spring container-managed singleton bean Component. The @repository, @Service, and @Controller annotation components are functional annotations for different usage scenarios.

Therefore, when you annotate a class with @Component, it means that you can also use @repository, @Service, and @Controller instead, and these annotations have a lot more functionality.

Finally, if you don’t know whether to use @Service or @Component annotations in the business layer of your project. Then @service is a better choice.

conclusion

This is a brief introduction to several Spring annotations and code examples that I personally use and don’t understand or ignore. Of course, this article is not completely introduced, and will continue to be supplemented and improved in the future.

link

  • 15 Classic Spring Interview Questions
  • Original | I picked up by the interviewer to abuse meng, because I don’t understand @ the Configuration in the Spring
  • Mastering Spring Boot — Chapter 15: Handling Exceptions using @ControllerAdvice