This is the sixth day of my participation in Gwen Challenge
1. @Component
和 @Bean
What is the difference between?
- Different objects:
@Component
Annotations apply to classes, and@Bean
Annotations apply to methods, @Component
Automatic detection and automatic assembly are usually done by path scanningSpring
In the container (we can use@ComponentScan
The annotation defines the path to scan to find the class that identifies the assembly to be automatically assembled toSpring
的bean
In the container).@Bean
Annotations are usually the ones we define in the method marked with the annotations that produce thisbean
.@Bean
Tell theSpring
This is an instance of some class, and we’ll give it back to me when we need it.@Bean
Annotations than@Component
Annotations are more customizable, and there are many places we can only pass@Bean
Annotations to registerbean
. For example, when we reference a third party library class that needs to be assembled intoSpring
Containers can only be passed through@Bean
To 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
和 @Resource
The difference between
@Autowire
和@Resource
Both can be used to assemble beans, and both can be used for fields or setter methods.@Autowire
The defaultAccording to the typeBy default, the dependent object must exist. If you want to allow null, you can set its required property to false.@Resource
The 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
- 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 that can mark any class asSpring
The component. This can be used if a Bean does not know which layer it belongs to@Component
Annotation 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@Bean
Methods.
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
@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 as
static
. @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.
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
.@Service
The 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