Spring’s JavaConfig annotation

  spring, spring-mvc

Order

Traditional spring is generally configured based on xml, but many comments of JavaConfig were added later. Springboot, in particular, is basically all java config. if you don’t understand it, you really don’t adapt. Note here.

@RestController

Spring4 has added RestController’s comments in order to more conveniently support the development of restfull applications. More functions than controller’s comments are to add ResponseBody comments to the following RequestMapping methods by default, so as to save yourself from adding the comments to each one.

@Configuration

This annotation class is spring’s configuration class and has its own Component annotation

@ImportResource

Corresponding xml

<import resource="applicationContext-ehcache.xml"/>

Necessity of existence

This is compatible with traditional xml configuration, after all JavaConfig is not universal, such asJavaConfig cannot support aop:advisor and tx:advice well.,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 functions of the following configurations:

<context:annotation-config/>

Is to register autowiredannotionbeanpostprocessor (You must register to use @ autowire.)、CommonAnnotationBeanPostProcessor(You must register to use @Resource, @PostConstruct, @PreDestroy, etc.)、PersistenceAnnotationBeanPostProcessor(You must register to use @PersistenceContext.) and requirednotionationbeanpostprocessor (You must register to use @Required) These 4 BeanPostProcessor.
It is worth noting thatSpring Spring3.1RC2Previously, it was not allowed to comment on the Configuration class within the package scope specified by ComponentScan, otherwise an error will be 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 defaultannotations handlermapping (To register the mapping relationship between handler method and request.) and AnnotationMethodHandlerAdapter (Handle its parameters before actually calling handler method.) two bean to support the use of @Controller annotations.
The main functions are as follows:

  • Configurable ConversionService (Convenient for Custom Type Conversion)

  • Formatting numeric type fields with @NumberFormat is supported.

  • Supports formatting Date,Calendar, and Joda Time fields with @DateTimeFormat (If classpath has Joda Time)

  • Support parameter verification for @Valid (If JSR-303 related provider are in classpath)

  • Support XML reading and writing of @RequestBody/@ResponseBody comments (If JAXB were in classpath)

  • Support JSON reading and writing of @RequestBody/@ResponseBody comments (If Jackson were in classpath)

@ContextConfiguration

Java config is mainly specified 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. The http return code returned by the annotation is shown in the ORG. Spring Framework. HTTP. HTTP Status enumeration for specific values. General post methods return HttpStatus.CREATED, DELETE and PUT methods return HttpStatus.OK You can also configure exception handling, see @ExceptionHandler and @ControllerAdvice

@ExceptionHandler

It is mainly used to handle the specified exception and return the specified HTTP status code so as to save each controller’s method from trying catch. Generally, an exception base class can be defined for each application, and then business exceptions can be defined, so that business exceptions 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 worth noting that this method is limited to exceptions generated by the controller’s method call chain. If timing tasks are also used in spring, the annotation will not be intercepted.

@ControllerAdvice

The method used with @ExceptionHandler to intercept the controller.

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