Java Spring Java config annotations

Source: Internet
Author: User

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:

 
 
  1. <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.

 
 
  1. @RunWith(SpringJUnit4ClassRunner.class) 
  2. @ContextConfiguration({ 
  3.     "classpath*:spring/*.xml", 
  4.     "classpath:applicationContext.xml", 
  5.     "classpath:applicationContext-rabbitmq.xml", 
  6.     "classpath:applicationContext-mail.xml", 
  7.     "classpath:applicationContext-medis.xml", 
  8.     "classpath:applicationContext-mybatis.xml"}) 
  9. @TransactionConfiguration(transactionManager = "mybatisTransactionManager", defaultRollback = false) 
  10. public class AppBaseTest { 
  11.    //...... 

@ 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.

 
 
  1. @ExceptionHandler(BizException.class) 
  2.  @ResponseStatus(HttpStatus.BAD_REQUEST) 
  3.  public @ResponseBody 
  4.  ReturnMessage bizExceptionHandler(Exception ex) { 
  5.      logger.error(ex.getMessage(),ex); 
  6.      return new ReturnMessage(HttpStatus.BAD_REQUEST.value(),ex.getMessage()); 
  7.  } 

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.

 
 
  1. @ControllerAdvice 
  2. public class ErrorController { 
  3.  
  4.     private static final Logger logger = LoggerFactory.getLogger(ErrorController.class); 
  5.  
  6.     @ExceptionHandler(BizException.class) 
  7.     @ResponseStatus(HttpStatus.BAD_REQUEST) 
  8.     public @ResponseBody 
  9.     ReturnMessage bizExceptionHandler(Exception ex) { 
  10.         logger.error(ex.getMessage(),ex); 
  11.         return new ReturnMessage(HttpStatus.BAD_REQUEST.value(),ex.getMessage()); 
  12.     } 
  13.  
  14.     @ExceptionHandler(Exception.class) 
  15.     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
  16.     public @ResponseBody 
  17.     ReturnMessage serverExceptionHandler(Exception ex) { 
  18.         logger.error(ex.getMessage(),ex); 
  19.         return new ReturnMessage(HttpStatus.INTERNAL_SERVER_ERROR.value(),ex.getMessage()); 
  20.     } 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.