Java Spring Java config annotations
Collation
Traditional spring is generally configured based on xml, but many JavaConfig annotations are added later. In particular, springboot is basically a clear java config. If you don't know about it, it's really not suitable. Note here.
@ RestController
Spring4 added the RestController annotation to support restfull application development more conveniently. The function that has more annotations than the Controller annotation is to add the ResponseBody annotation to the RequestMapping method below by default, you do not have to add this annotation to each annotation.
@ Configuration
This annotation class is spring's configuration class, with its own Component Annotation
@ ImportResource
Corresponding xml
<Import resource = "applicationContext-ehcache.xml"/>
Necessity
This is compatible with traditional xml configurations. After all, JavaConfig is not omnipotent. For example, JavaConfig does not support aop: advisor and tx: advice, Introduce @ EnableAspectJAutoProxy (equivalent to aop: aspectj-autoproxy), Introduce @ Configuration-based equivalent to aop: config XML element
@ ComponentScan
Corresponding xml
<Context: component-scan base-package = "com. xixicat. app"/>
This configuration automatically includes the following configuration features:
<Context: annotation-config/>
It is to register AutowiredAnnotationBeanPostProcessor with the Spring container (@ Autowired must be registered), CommonAnnotationBeanPostProcessor (must be registered with @ Resource, @ PostConstruct, @ PreDestroy, etc) and RequiredAnnotationBeanPostProcessor (@ Required must be registered.
It is worth noting that Spring3.1RC2 does not allow the Configuration annotation class to be within the package range specified by ComponentScan. Otherwise, an error is reported.
@ Bean
The corresponding xml is as follows:
- <bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
@ EnableWebMvc
The corresponding xml is as follows:
<Mvc: annotation-driven/>
This configuration automatically registers two beans: DefaultAnnotationHandlerMapping (to register the mapping relationship between handler method and request) and AnnotationMethodHandlerAdapter (to process the parameters before actually calling the handler method, to support the use of @ Controller annotations.
The main functions are as follows:
-
Configurable ConversionService (for easy conversion of custom types)
-
Supports formatting numeric fields with @ NumberFormat
-
Supports formatting Date, Calendar, and Joda Time fields with @ DateTimeFormat (if classpath has Joda Time)
-
Supports Parameter validation for @ Valid (if the JSR-303-related provider is in classpath)
-
Supports @ RequestBody/@ ResponseBody annotation XML read/write (if JAXB is in classpath)
-
Support @ RequestBody/@ ResponseBody annotation JSON read/write (if Jackson is in classpath)
@ ContextConfiguration
Specify java config during junit testing.
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration({
- "classpath*:spring/*.xml",
- "classpath:applicationContext.xml",
- "classpath:applicationContext-rabbitmq.xml",
- "classpath:applicationContext-mail.xml",
- "classpath:applicationContext-medis.xml",
- "classpath:applicationContext-mybatis.xml"})
- @TransactionConfiguration(transactionManager = "mybatisTransactionManager", defaultRollback = false)
- public class AppBaseTest {
- //......
- }
@ ResponseStatus
It is mainly used for rest development and the http return code returned by the annotation. For specific values, refer to the org. springframework. http. HttpStatus enumeration. Generally, the post method returns HttpStatus. CREATED, and the DELETE and PUT Methods return HttpStatus. OK. You can also configure Exception Handling. For details, see @ ExceptionHandler and @ ControllerAdvice.
@ ExceptionHandler
It is mainly used to handle specified exceptions, return the specified HTTP status code, and save each controller method to try catch. Generally, you can define an exception base class for each application, and then define business exceptions. In this way, you can capture business exceptions in a unified manner.
- @ExceptionHandler(BizException.class)
- @ResponseStatus(HttpStatus.BAD_REQUEST)
- public @ResponseBody
- ReturnMessage bizExceptionHandler(Exception ex) {
- logger.error(ex.getMessage(),ex);
- return new ReturnMessage(HttpStatus.BAD_REQUEST.value(),ex.getMessage());
- }
However, it is worth noting that this method is limited to the exceptions generated by the controller's method call chain. If a scheduled task is used in spring, This annotation will not be intercepted.
@ ControllerAdvice
Used with @ ExceptionHandler to intercept the controller method.
- @ControllerAdvice
- public class ErrorController {
-
- private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);
-
- @ExceptionHandler(BizException.class)
- @ResponseStatus(HttpStatus.BAD_REQUEST)
- public @ResponseBody
- ReturnMessage bizExceptionHandler(Exception ex) {
- logger.error(ex.getMessage(),ex);
- return new ReturnMessage(HttpStatus.BAD_REQUEST.value(),ex.getMessage());
- }
-
- @ExceptionHandler(Exception.class)
- @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
- public @ResponseBody
- ReturnMessage serverExceptionHandler(Exception ex) {
- logger.error(ex.getMessage(),ex);
- return new ReturnMessage(HttpStatus.INTERNAL_SERVER_ERROR.value(),ex.getMessage());
- }
- }