详细解说Java Spring的JavaConfig注解

开发 前端
传统spring一般都是基于xml配置的,不过后来新增了许多JavaConfig的注解。特别是springboot,基本都是清一色的java config,不了解一下,还真是不适应。这里备注一下。

传统spring一般都是基于xml配置的,不过后来新增了许多JavaConfig的注解。特别是springboot,基本都是清一色的java config,不了解一下,还真是不适应。这里备注一下。

[[161315]]

@RestController

spring4为了更方便的支持restfull应用的开发,新增了RestController的注解,比Controller注解多的功能就是给底下的RequestMapping方法默认都加上ResponseBody注解,省得自己再去每个去添加该注解。

@Configuration

这个标注该类是spring的配置类,本身自带Component注解

@ImportResource

对应的xml

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

存在的必要性

这个是兼容传统xml配置的,毕竟JavaConfig还不是***的,比如 JavaConfig不能很好地支持aop:advisor和tx:adviceIntroduce @EnableAspectJAutoProxy (equivalent to aop:aspectj-autoproxy)Introduce @Configuration-based equivalent to aop:config XML element

@ComponentScan

对应的xml

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

该配置自动包含了如下配置的功能:

<context:annotation-config/>

就是向Spring容器注册AutowiredAnnotationBeanPostProcessor( 使用@Autowired必须注册 )、CommonAnnotationBeanPostProcessor( 使用@Resource 、@PostConstruct、@PreDestroy等必须注册 )、PersistenceAnnotationBeanPostProcessor( 使用@PersistenceContext必须注册 ) 以及RequiredAnnotationBeanPostProcessor( 使用@Required必须注册 )这4个BeanPostProcessor。

值得注意的是 Spring3.1RC2版本 是不允许注解Configuration的类在ComponentScan指定的包范围内的,否则会报错。

@Bean

对应的xml如下:

  1. <bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper" /> 

@EnableWebMvc

对应的xml如下:

<mvc:annotation-driven />

该配置自动注册DefaultAnnotationHandlerMapping( 来注册handler method和request的mapping关系 )与AnnotationMethodHandlerAdapter( 在实际调用handler method前对其参数进行处理 )两个bean,以支持@Controller注解的使用。

主要的作用如下:

  • 可配置的ConversionService(方便进行自定义类型转换)

  • 支持用@NumberFormat格式化数字类型字段

  • 支持用@DateTimeFormat格式化Date,Calendar以及Joda Time字段( 如果classpath有Joda Time的话 )

  • 支持@Valid的参数校验( 如果JSR-303相关provider有在classpath的话 )

  • 支持@RequestBody/@ResponseBody注解的XML读写( 如果JAXB在classpath的话 )

  • 支持@RequestBody/@ResponseBody注解的JSON读写( 如果Jackson在classpath的话 )

@ContextConfiguration

主要在junit测试时指定java config

  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

主要是rest开发用,注解返回的http返回码,具体值看org.springframework.http.HttpStatus枚举。一般 post方法返回HttpStatus.CREATED,DELETE和PUT方法返回HttpStatus.OK。还可以配置异常处理,见 @ExceptionHandler和@ControllerAdvice

@ExceptionHandler

主要用来处理指定的异常,返回返回指定的HTTP状态码,省得每个controller的方法自己去try catch。一般可以为每个应用定义一个异常基类,然后再定义业务异常,这样这里就可以统一捕获业务异常。

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

不过值得注意的是这种方法仅限于controller的方法调用链产生的异常,如果在spring里头还使用了定时任务啥的,该注解是不会拦截到的。

@ControllerAdvice

配合@ExceptionHandler使用的,用来拦截controller的方法。

 

  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.     } 
责任编辑:王雪燕 来源: segmentfault
相关推荐

2021-04-13 20:24:57

Spring Boot注解spring

2010-07-09 10:54:23

SQLServer字段

2009-01-09 22:29:38

服务器虚拟化磁盘阵列

2010-02-04 15:01:07

Android架构

2015-09-18 10:57:45

Web网页性

2010-02-05 16:58:18

Android服务

2010-02-25 14:50:59

Linux文件系统

2009-12-31 13:56:57

ADO访问接口

2011-06-02 12:34:16

正则表达式

2009-12-21 13:19:34

ADO.NET组件

2011-07-20 17:54:02

C++

2016-03-21 17:08:54

Java Spring注解区别

2010-03-19 10:19:42

第四层交换

2009-12-16 09:56:30

Fedora Gnom

2009-12-31 11:27:33

2022-06-09 07:27:14

JavaSpring容器

2009-12-31 09:54:04

ADO.NET数据访问

2011-03-01 16:11:52

思科路由交换

2009-07-15 16:11:26

光纤技术布线

2011-02-28 17:33:19

光纤
点赞
收藏

51CTO技术栈公众号