---
title: "Spring注解笔记"
author: "xiaowei2002"
date: "2015-07-22T14:33:30Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2015-07-23T17:42:15Z"
id: 2229353
url: "https://xiaowei2002.iteye.com/blog/2229353"
---

Spring注解  
1、spring  @Order 注解  
利用 @Order 控制配置类的加载顺序，值越小越先加载。  
2、Spring 注解@Component,@Service,@Controller,@Repository  
Spring 2.5 中除了提供 @Component 注释外，还定义了几个拥有特殊语义的注释，  
它们分别是：@Repository、@Service 和 @Controller。  
在目前的 Spring 版本中，这 3 个注释和 @Component 是等效的，  
但是从注释类的命名上，很容易看出这 3 个注释分别和持久层、业务层和控制层（Web 层）相对应搜索。  
虽然目前这 3 个注释和 @Component 相比没有什么新意，但 Spring 将在以后的版本中为它们添加特殊的功能。  
所以，如果 Web 应用程序采用了经典的三层分层结构的话，  
最好在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller  
对分层中的类进行注释，而用 @Component 对那些比较中立的类进行注释。

注解本身使用@Controller和@ResponseBody注解。使用了这个注解的类会被看作一个controller-使用@RequestMapping的方法有一个默认的@ResponseBody注解。  

\-----------------------------------------  
\-------------------------------------------------------------------  
@Service注释表示定义一个bean，自动根据bean的类名实例化一个首写字母为小写的bean  
,例如Chinese实例化为chinese，American实例化为american  
，如果需要自己改名字则:@Service("你自己改的bean名")。

\----------------------------------------------------------------  
3、Spring 在接口前面标上@Autowired和@Qualifier注释使得接口可以被容器注入  
Spring 2.5 引入了@Autowired 注释，它可以对类成员变量、方法及构造函数进行标注，完  
成自动装配的工作。当接口存在两个实现类的时候必须指定其中一个来注入，使用实现类首字母小写的字符串来注入，  
Spring 通过一个BeanPostProcessor 对@Autowired 进行解析，所以要让@Autowired 起作用必须事先在Spring  
容器中声明AutowiredAnnotationBeanPostProcessor Bean。  
如：   @Autowired       @Qualifier("chinese")          
 private Man man;   使用Autowired注入的步骤：  
 1.首先根据类型找到所有可以满足条件的bean2.判断bean长度，  
 如果没有，则根据@autowired中的required属性进行判断是否抛出异常(默认为true)3.如果多于一个，  
则尝试寻找最优的那一个，如果最优的未找到，则抛出异常.  
如果只有一个，则直接使用此bean 否则可以省略，只写@Autowired   。

\--------------------------------------------------------------------------------------------------

4.0重要的一个新的改进是@RestController注解，它继承自@Controller注解。

当你实现一个RESTful web services的时候，response将一直通过response body发送。为了简化开发，Spring 4.0提供了一个专门版本的controller.下面我们来看看@RestController实现的定义：

 

Java代码 [![复制代码](http://wiselyman.iteye.com/images/icon_copy.gif)](http://wiselyman.iteye.com/blog/2002446 "复制代码") [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)![](http://wiselyman.iteye.com/images/spinner.gif)]()

1. @Target(value=TYPE)
2. @Retention(value=RUNTIME)
3. @Documented
4. @Controller
5. @ResponseBody
6. public @interface RestController

spring @RestController 直接返回值