20+ Spring common notes that Java development must master

The annotation itself has no function, just like xml. Annotations and XML are both types of metadata. Metadata is data that explains data. This is called configuration.

This article mainly lists the introduction of Spring | SpringMVC related annotations.
Spring section

1. Annotate the bean annotation

@Component component, no explicit role

@Service is used in the business logic layer (service layer)

@Repository used in the data access layer (dao layer)

@Controller used in the presentation layer, the declaration of the controller (Controller layer)

2. Annotation of injected beans

@Autowired: Spring, according to the type, in variables, setter methods, constructors;

@Inject: JSR-330, according to the type (@Name according to the name), on variables, setter methods, constructors;

@Resource: JSR-250, according to the name (specify the name attribute), in the variable, setter method.

Both can be annotated on the set method and attributes. It is recommended to annotate the attributes (at a glance, write less code).

For the ambiguity problem of @Autowired, see @Autowired detailed explanation-three implementation methods, multiple ambiguity solutions
@Qualifier and @Primary can be used for bean ambiguity problems

3. Annotations on java configuration classes

@Configuration declares that the current class is a configuration class, which is equivalent to the Spring configuration in xml form (on the class)

@Bean annotation on the method, declare that the return value of the current method is a bean, instead of the way in xml (on the method)

@Configuration declares the current class as the configuration class, which internally combines the @Component annotation, indicating that this class is a bean (on the class)

@ComponentScan is used to scan Component, which is equivalent to context: component-scan / in xml (on the class)

@WishlyConfiguration is a combined annotation of @Configuration and @ComponentScan, which can replace these two annotations

4. Annotations on AOP

Spring supports AspectJ's annotated aspect programming.

@Aspect declares an aspect (on the class).
Use @After, @Before, @Around to define advice, and you can directly take the interception rule (cut point) as a parameter.

@After executed after method execution (on method)
@Before executed before method execution (on method)
@Around executed before and after method execution (on method)

@PointCut declares pointcuts
. Use the @EnableAspectJAutoProxy annotation in the java configuration class to enable Spring's support for AspectJ proxy (on the class)

5. @Bean attribute support

@Scope sets how the Spring container creates a new Bean instance (method, there must be @Bean).
Its setting types include:

Singleton (singleton, there is only one bean instance in a Spring container, the default mode),
Protetype (each call creates a new bean),
Request (in a web project, create a new bean for each http request),
Session (in a web project, Create a new bean for each http session),
GlobalSession (create a new bean instance for each global http session)

@StepScope is also involved in Spring Batch

@PostConstruct Provided by JSR-250, executed after the constructor is executed, equivalent to the initMethod of the bean in the xml configuration file

@PreDestory Provided by JSR-250, executed before the bean is destroyed, equivalent to the destroyMethod of the bean in the xml configuration file

6. @Value annotation

@Value injects values ​​for attributes (on attributes) and
supports the following injections:

  • Inject ordinary characters
@Value("Michael Jackson")
String name;
  • Inject operating system attributes
@Value("#{systemProperties['os.name']}")
String osName;
  • Inject expression results
@Value("#{ T(java.lang.Math).random() * 100 }")
String randomNumber;
  • Inject other bean properties
@Value("#{domeClass.name}")
String name;
  • Inject file resources
@Value("classpath:com/hgs/hello/test.txt")
String Resource file;
  • Inject website resources
@Value("http://www.cznovel.com")
Resource url;
  • Inject configuration file
@Value("${book.name}")
String bookName;

Injection configuration usage method:

  1. Write a configuration file (test.properties)
book.name=《三体》
  1. @PropertySource load configuration file (on the class)
@PropertySource("classpath:com/hgs/hello/test/test.propertie")
  1. You also need to configure a PropertySourcesPlaceholderConfigurer bean.

7. Environment switching

@Profile By setting the ActiveProfiles of Environment to set the configuration environment that the current context needs to use. (On the class or method)

@Conditional Spring4 can use this annotation to define the conditional bean, by implementing the Condition interface, and rewriting the matches method to determine whether the bean is instantiated. (Methodologically)

8. Asynchronous correlation

@EnableAsync configuration class, through this annotation to open support for asynchronous tasks, narrative AsyncConfigurer interface (on the class)

@Async uses this annotation in the actual bean method to declare that it is an asynchronous task (all methods on the method or class will be asynchronous, and @EnableAsync is required to start the asynchronous task)

9. Related to scheduled tasks

@EnableScheduling is used on the configuration class to enable support for scheduled tasks (on the class)

@Scheduled to declare that this is a task, including cron, fixDelay, fixRate and other types (method, you need to open the support of scheduled tasks first)

10. @ Enable * annotation description

These annotations are mainly used to enable support for xxx.

  • @EnableAspectJAutoProxy Turn on support for AspectJ automatic proxy

  • @EnableAsync Turn on asynchronous method support

  • @EnableScheduling Turn on support for scheduled tasks

  • @EnableWebMvc Turn on Web MVC configuration support

  • @EnableConfigurationProperties Turn on support for @ConfigurationProperties annotation configuration beans

  • @EnableJpaRepositories enable support for SpringData JPA Repository

  • @EnableTransactionManagement enables support for annotated transactions

  • @EnableTransactionManagement enables support for annotated transactions

  • @EnableCaching Turn on annotated caching support

11. Test related notes

  • @RunWith Runner, usually used to support JUnit in Spring

  • @RunWith(SpringJUnit4ClassRunner.class)

  • @ContextConfiguration is used to load the configuration ApplicationContext, where the classes attribute is used to load the configuration class

  • @ContextConfiguration(classes={TestConfig.class})

12. The SpringMVC part
@EnableWebMvc enables Web MVC configuration support in the configuration class, such as some ViewResolver or MessageConverter, etc. If there is no such sentence, rewrite the WebMvcConfigurerAdapter method (used to configure SpringMVC).

@Controller declares this class as a Controller in Spring MVC, and for front-end debugging, and @RestController for monotonous background use

@RestController The annotation is a combined annotation, which is equivalent to the combination of @Controller and @ResponseBody. The annotation is on the class, which means that all methods of this Controller are added by default @ResponseBody.
The view resolver InternalResourceViewResolver configured in it does not work, the method cannot return to the jsp page, or html, and returns String / Json.

@RequestMapping is used to map Web requests, including access paths and parameters (on classes or methods)

@ResponseBody supports putting the return value in the response instead of a page, usually the user returns json data (beside the return value or on the method)

@RequestBody allows the parameters of the request to be in the request body, not directly after the address. (Before the parameter)

@PathVariable is used to receive path parameters, such as the path declared by @RequestMapping ("/ hello / {name}"), and the value can be obtained before the note is placed in the parameter. It is usually used as a Restful interface implementation method.

@RequestRaram is used to pass parameters and values, and can be placed before attributes or method parameters. (1) value The parameter name of the request parameter is used as the parameter mapping name; (2) required Whether the parameter is required, the default is true (required), when set to required, if there is no incoming parameter, an error will be reported; (3) defaultValue sets the default value of the request parameter;

@ControllerAdvice by the annotation, we can place the profile for the global controller in the same position, the annotation @Controller method, can be utilized @ ExceptionHandler, @ InitBinder, @ ModelAttribute annotation to the method,
which all annotated! The method in the controller of RequestMapping is effective.

@ExceptionHandler is used to handle exceptions in the controller globally

@InitBinder is used to set WebDataBinder, and WebDataBinder is used to automatically bind the foreground request parameters to the Model.

The original role of @ModelAttribute is to bind key-value pairs to the Model. In @ControllerAdvice, the global @RequestMapping can get the key-value pairs set here.

@CrossOrigin is used to solve cross-domain problems, just declare on the interface, instead of filters or interception methods.

If there are any omissions or errors, I hope to help point out.

13. SpringBoot part
@ServletComponentScan After using @ServletComponentScan annotation on SpringBootApplication, Servlet, Filter and Listener can be directly registered through @WebServlet, @WebFilter and @WebListener annotation without additional code.

————————————————
Copyright Statement: This article is an original article of CSDN blogger "IT_faquir", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprint .
Original link: https://blog.csdn.net/IT_faquir/article/details/78025203

Published 17 original articles · praised 0 · visits 215

Guess you like

Origin blog.csdn.net/neheqi/article/details/105430126