Javaconfig Annotations for Java Spring

Source: Internet
Author: User
Tags try catch

Order

Traditional spring is generally based on XML configuration, but a lot of javaconfig annotations have been added later. Especially Springboot, basically are the Java config of exclusively, do not understand, still really do not adapt. Here's a note.

@RestController

Spring4 in order to more easily support the development of restfull applications, added Restcontroller annotations, more than the controller annotation function is to the bottom of the Requestmapping method by default, plus responsebody annotations, Save yourself from going to each other to add the note.

@Configuration

This annotation class is spring's configuration class, with its own component annotations

@ImportResource the corresponding XML
<import resource= "Applicationcontext-ehcache.xml"/>
The necessity of existence

This is compatible with the traditional XML configuration, after all, Javaconfig is not omnipotent, such as javaconfig can not well support aop:advisor and Tx:advice, introduce @EnableAspectJAutoProxy ( Equivalent to Aop:aspectj-autoproxy), introduce @Configuration-based equivalent to aop:config XML element

@ComponentScan

The corresponding XML

<context:component-scan base-package= "Com.xixicat.app"/>

This configuration automatically includes the following configuration features:

<context:annotation-config/>

is to register autowiredannotationbeanpostprocessor with the spring container (using @autowired must be registered), Commonannotationbeanpostprocessor ( Use @resource, @PostConstruct, @PreDestroy, etc. must be registered), Persistenceannotationbeanpostprocessor (use @persistencecontext must register) and requiredannotationbeanpostprocessor (use @required must register) these 4 beanpostprocessor.

It is noteworthy that the SPRING3.1RC2 version is a class that does not allow the annotation configuration to be within the range specified by Componentscan, otherwise an error will be given.

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

The configuration automatically registers defaultannotationhandlermapping (to register the mapping relationship of handler method and request) with Annotationmethodhandleradapter ( Two beans to support the use of the @controller annotations before actually calling handler method to process their arguments.

The main functions are as follows:

    • Configurable ConversionserVice (for easy custom type conversions)
    • Support for formatting numeric type fields with @numberformat
    • Support for formatting Date,calendar and Joda Time fields with @datetimeformat (if Classpath has Joda time)
    • Supports @valid parameter checking (if JSR-303 related provider is in classpath)
    • Supports @requestbody/@ResponseBody annotations for XML reading and writing (if JAXB is in classpath)
    • JSON read/write support for @requestbody/@ResponseBody annotations (if Jackson is in classpath)
@ContextConfiguration

Specifying Java config primarily 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

Mainly for rest development, the annotations return the HTTP return code, the exact value of the Org.springframework.http.HttpStatus enumeration. The General Post method returns Httpstatus.created,delete and the Put method returns Httpstatus.ok. You can also configure exception handling, see @exceptionhandler and @controlleradvice

@ExceptionHandler

It is mainly used to handle the specified exception, return the specified HTTP status code, and save each controller's way to try catch itself. You can typically define an exception base class for each application, and then define a business exception so that the business exception can be captured uniformly here.

    @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 important to note that this method is limited to the exception generated by the controller's method call chain, which is not intercepted if a timed task is used in spring.

@ControllerAdvice

A method used in conjunction with @exceptionhandler to intercept a controller.

@ControllerAdvicepublic 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 ());}    }

Javaconfig Annotations for Java Spring

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.