Detail the JavaConfig annotation in Spring

  • 2020-06-03 06:31:53
  • OfStack

preface

It is well known that traditional spring1 is generally based on xml configuration, but many JavaConfig annotations have been added. springboot, in particular, is basically clear and 1 color java config, do not know 1, is really not used to. Note 1 here.

@RestController

spring4 added RestController annotations to support the development of restfull applications more easily than Controller annotations. The additional function of spring4 is to add ResponseBody annotations to the RequestMapping methods below by default, saving you from having to add the annotations to each of them.

@Configuration

This annotation class is the configuration class of spring and comes with its own Component annotations

@ImportResource

The corresponding xml


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

Necessity of existence

This is compatible with traditional xml configuration, after all JavaConfig is not a panacea, JavaConfig does not support aop:advisor and tx:advice, Introduce @EnableAspectJAutoProxy (equivalent to aop: ES54en-ES55en), ES56en@Introduce aop config element

@ComponentScan

The corresponding xml


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

This configuration automatically includes the following configuration features:


<context:annotation-config/>

This is to register AutowiredAnnotationBeanPostProcessor with the Spring container (@Autowired must be registered), CommonAnnotationBeanPostProcessor(@Resource, @PostConstruct, @PreDestroy, etc.), PersistenceAnnotationBeanPostProcessor(@PersistenceContext must be registered) and RequiredAnnotationBeanPostProcessor(@ES88en must be registered).

Note that es92EN3.1RC2 does not allow classes that annotate Configuration to be in the package 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 DefaultAnnotationHandlerMapping(to register the mapping relationship between handler method and request) and AnnotationMethodHandlerAdapter(to process its parameters before actually calling handler method) to support the use of the @Controller annotation.

The main functions are as follows:

Configurable ConversionService(easy for custom type conversion) Support for formatting numeric type fields with @NumberFormat Support for formatting Date,Calendar and Joda Time fields with @ES129en (if classpath has Joda Time) Support parameter validation for @Valid (if JSR-303 related provider is in classpath) Support @ES141en / @ES142en annotation for XML reading and writing (if JAXB is in classpath) Support @ES146en / @ES147en annotated JSON read and write (if Jackson is 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

Mainly rest development use, annotation the returned http return code, specific values. See org springframework. http. HttpStatus enumeration. 1 General post methods return ES174en. CREATED, DELETE and PUT methods return ES178en. OK. You can also configure exception handling, as shown in @ExceptionHandler and @ES181en

@ExceptionHandler

Returns the specified HTTP status code, saving each controller method from going to try itself. It is generally possible to define an exception base class for each application, and then define business exceptions so that business exceptions can be caught 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());
 }

It is worth noting, however, that this method is limited to exceptions generated by controller's method call chain, and the annotation would not have been intercepted if timing tasks were used in spring.

@ControllerAdvice

The method used to intercept controller in conjunction with @ES203en.


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

conclusion

The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.


Related articles: