This article looks at a few Spring annotations that aren’t easy to tell the difference or use, such as @Component versus @bean, how @ControllerAdvice handles custom exceptions, and so on.
Some annotations in Spring
1. What is the difference between @Component and @bean?
-
The @Component annotation applies to classes, while the @bean annotation applies to methods,
-
The @Component is automatically detected and assembled into the Spring container by path scanning (we can use the @ComponentScan annotation to define the path to be scanned to identify classes that need to be assembled into the Spring bean container). The @bean annotation is usually what we define in the method marked with the annotation to generate the Bean. The @bean tells Spring that this is an instance of a class, and gives it back to me when we need to use it.
-
The @Bean annotation is more customizable than the @Component annotation, and in many places we can only register beans through the @Bean annotation. For example, when we reference a class from a third-party library that needs to be assembled into the Spring container, we can only do so through @Beans.
Example use of @bean annotations:
@Configuration public class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(); }}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 new serviceImpl3(); }}Copy the code
2. The difference between Autowire and @Resource
-
Both @Autowire and @Resource can be used to assemble beans, and both can be used for fields or setter methods. Spring Boot study notes to share with you.
-
By default, @autowire must be assembled by type. By default, the dependent object must exist. To allow null values, you can set its required property to false.
-
@Resource is assembled by name by default 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
-
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.
-
If the name attribute is specified, an exception is thrown if the assembly of beans whose names match is not found in the container.
-
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;
-
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 for any spring-class Component. If a Bean does not know which layer it belongs to, it can be annotated using the @Component annotation.
-
@repository: Corresponds to the persistence layer (Dao layer), which is used for database-related operations.
-
@service: corresponding to the Service layer, mainly designed 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 in which one or more @bean methods can be declared.
4. @Configuration: Configures 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() { // 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, so the @Configuration class can also be scanned by components (especially elements that use 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 static.
-
The @bean method 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.
Spring Boot: github.com/javastacks/…
5. @ControllerAdvice: Handle 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. Spring Boot study notes to share with you.
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 {/ capture CustomException * * * * * @ param e @return JSON format */ @responseBody @ExceptionHandler({customException.class}) // Specifies the type of exception to intercept @responseStatus (httpstatus. INTERNAL_SERVER_ERROR) public Map>String, Object< customExceptionHandler(CustomException e) { Map< String, Object> map = new HashMap< > (a); map.put("code", e.getCode()); map.put("msg", e.getMsg()); return map; }}Copy the code
See the official documentation for Spring @ControllerAdvice for more information. Spring Boot: github.com/javastacks/…
6. @Component, @repository, @service
@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.