Home > Java > javaTutorial > body text

Detailed introduction to JavaConfig annotations in Spring

黄舟
Release: 2017-03-09 11:01:24
Original
1381 people have browsed it

When developing Java programs, especially Java EE applications, it is always inevitable to deal with various configuration files. Java annotations help us make it tidier and prevent configuration files from flying all over the place. The following article mainly introduces the JavaConfig annotations in Spring in detail. Friends who need it can refer to it. Let’s take a look together.

Preface

Everyone knows that traditional spring is generally based on xml configuration, but later many JavaConfig annotations were added. Especially for springboot, it is basically all java config. If you don’t understand it, you are really not used to it. Make a note here.

@RestController

In order to more conveniently support the development of restfull applications, spring4 has added RestController annotations. The functions that have more annotations than Controller are given below The RequestMapping method adds the ResponseBody annotation by default, saving you the need to add the annotation to each one.

@Configuration

This annotation indicates that this class is a spring configuration class, and it comes with its own Component annotation

@ImportResource

Corresponding xml

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

Necessity of existence

This It is compatible with traditional xml configuration. After all, JavaConfig is not omnipotent. For example, JavaConfig 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"/>
Copy after login

The The configuration automatically includes the following configuration functions:

<context:annotation-config/>
Copy after login

is to register AutowiredAnnotationBeanPostProcessor (required to use @Autowired), CommonAnnotationBeanPostProcessor (using @Resource, @PostConstruct) with the Spring container , @PreDestroy, etc. must be registered), PersistenceAnnotationBeanPostProcessor (must be registered when using @PersistenceContext) and RequiredAnnotationBeanPostProcessor (must be registered when using @Required).

It is worth noting that the Spring 3.1RC2 version does not allow classes annotated with Configuration to be 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" />
Copy after login

@EnableWebMvc

The corresponding xml is as follows:

<mvc:annotation-driven />
Copy after login

This configuration automatically registers DefaultAnnotationHandlerMapping(( to register handler method and request mapping relationship) and AnnotationMethodHandlerAdapter (which processes the parameters of the handler method before actually calling it) two beans to support the use of @Controller annotations.

The main functions are as follows:

  1. Configurable ConversionService (convenient for custom type conversion)

  2. Support using @ NumberFormat formats numeric type fields

  3. Supports using @DateTimeFormat to format Date, Calendar and Joda Time fields (if the classpath has Joda Time)

  4. Support @Valid parameter verification (if the JSR-303 related provider is on the classpath)

  5. Support XML reading and writing of @RequestBody/@ResponseBody annotations (if JAXB is on the classpath)

  6. Support JSON reading and writing of @RequestBody/@ResponseBody annotations (if Jackson is on the classpath)

@ContextConfiguration

Mainly 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 {
 //......
}
Copy after login

@ResponseStatus

Mainly used for REST development. Annotate the http return code returned. For specific values, see 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, see @ExceptionHandler and @ControllerAdvice

@ExceptionHandler

is mainly used to handle specified exceptions and return the specified HTTP status code , saving each controller method its own try catch. Generally, you can define an exception base class for each application, and then define business exceptions, so that business exceptions can be captured uniformly.

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

However, it is worth noting that this method is limited to exceptions generated by the controller's method call chain. If scheduled tasks are also 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());
 }
}
Copy after login

Summary

The above is the detailed content of Detailed introduction to JavaConfig annotations in Spring. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!