前言
大家都知道傳統spring一般都是基于xml配置的,不過后來新增了許多JavaConfig的注解。特別是springboot,基本都是清一色的java config,不了解一下,還真是不適應。這里備注一下。
@RestController
spring4為了更方便的支持restfull應用的開發,新增了RestController的注解,比Controller注解多的功能就是給底下的RequestMapping方法默認都加上ResponseBody注解,省得自己再去每個去添加該注解。
@Configuration
這個標注該類是spring的配置類,本身自帶Component注解
@ImportResource
對應的xml
1
|
< import resource= "applicationContext-ehcache.xml" /> |
存在的必要性
這個是兼容傳統xml配置的,畢竟JavaConfig還不是萬能的,比如 JavaConfig不能很好地支持aop:advisor和tx:advice , Introduce @EnableAspectJAutoProxy (equivalent to aop:aspectj-autoproxy) ,Introduce @Configuration-based equivalent to aop:config XML element
@ComponentScan
對應的xml
1
|
<context:component-scan base- package = "com.xixicat.app" /> |
該配置自動包含了如下配置的功能:
1
|
<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如下:
1
|
<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
2
3
4
5
6
7
8
9
10
11
12
|
@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
主要是rest開發用,注解返回的http返回碼,具體值看org.springframework.http.HttpStatus枚舉。一般post方法返回HttpStatus.CREATED,DELETE和PUT方法返回HttpStatus.OK。還可以配置異常處理,見@ExceptionHandler和@ControllerAdvice
@ExceptionHandler
主要用來處理指定的異常,返回返回指定的HTTP狀態碼,省得每個controller的方法自己去try catch。一般可以為每個應用定義一個異常基類,然后再定義業務異常,這樣這里就可以統一捕獲業務異常。
1
2
3
4
5
6
7
|
@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()); } |
不過值得注意的是這種方法僅限于controller的方法調用鏈產生的異常,如果在spring里頭還使用了定時任務啥的,該注解是不會攔截到的。
@ControllerAdvice
配合@ExceptionHandler使用的,用來攔截controller的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@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()); } } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。