---
title: "Spring的注解积累"
author: "dream_ait"
date: "2015-06-26T14:44:03Z"
tags: []
categories: ["编程语言"]
slug: "spring"
draft: false
lastmod: "2015-06-26T14:45:23Z"
id: 2222296
url: "https://ait.iteye.com/blog/2222296"
---

转载：http://yijiesuifeng.iteye.com/blog/2221858

用注解来向Spring容器注册Bean。
 
需要在applicationContext.xml中注册：
Java代码  收藏代码

```java
<context:component-scan base-package=”pagkage1[,pagkage2,…,pagkagen]”/>。 
```
 
如：在base-package指明一个包   
Java代码  收藏代码

```java
<context:component-scan base-package="cn.wind"/>  
```

也可以在<context:component-scan base-package=” ”/>中指定多个包，如：
Java代码  收藏代码

```java
<context:component-scan base-package="cn.wind.dao.impl,cn.wind.service.impl,cn.wind.action"/>  
```

 
随时补充==========
 
1：@Repository 标注在持久层，即dao，用于标注数据访问。
 
2：@Service 标注在业务层，即service，用于标注业务逻辑。
 
3：@Controller 标注在控制层。
 
4：@Component 当不明确这个类属于那个层的时候，可以使用@Component进行标注，但不建议使用
 
5：@Autowired 属性加上@Autowired后不需要getter()和setter()方法，Spring会自动注入。
@Autowired(required=false)表示，如果spring上下文中没有找到该类型的bean时，才会使用new ServiceImpl(); 
 
6：@Qualifier 
当接口存在两个实现类的时候必须使用@Qualifier指定注入哪个实现类，否则可以省略，只写@Autowired。
 
例如：定义一个交通工具类：Vehicle。此时有两个子类Bus和Sedan。如果用@Autowired来找Vehicle的话，会有两个匹配的选项Bus和Sedan。为了限定选项，可以如下
Java代码  收藏代码

```java

@Autowired  
@Qualifier("bus")  
private Vehicle vehicle;  

```
 
@Qualifier("XXX") 中的XXX是 Bean 的名称，所以 @Autowired 和 @Qualifier 结合使用时，自动注入的策略就从 byType 转变成 byName 了。
 
7：形似@Service("xXX")：相当于讲这个类定义为一个bean，bean名称为xXX，默认为首字母小写
比如在一个Student实现类上加上@Service("student")，括号里面就是给实例化后的Student对象取个名字。这是在你一个接口有多个实现类的情况下区分实现类的方式。
比如Student实现了Person接口，在你的controller里面@Autowired Person时，假如这时Person还有另一个实现类User，为了确定实例化Student还是User， @Service括号里面的东西就有用了，
Java代码 

```java

@Autowired  
@Qualifier("student")  
private Person person;  

```
 
 
 
这样就确定实例化了一个Person指向一个Student对象。
 
8：@Resource
@Resource的作用相当于@Autowired，只不过@Autowired按byType自动注入，而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的，分是name和type，Spring将@Resource注解的name属性解析为bean的名字，而type属性则解析为bean的类型。所以如果使用name属性，则使用byName的自动注入策略，而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性，这时将通过反射机制使用byName自动注入策略。
 
@Resource装配顺序
1).如果同时指定了name和type，则从Spring上下文中找到唯一匹配的bean进行装配，找不到则抛出异常
2) 如果指定了name，则从上下文中查找名称（id）匹配的bean进行装配，找不到则抛出异常
3) 如果指定了type，则从上下文中找到类型匹配的唯一bean进行装配，找不到或者找到多个，都会抛出异常
4) 如果既没有指定name，又没有指定type，则自动按照byName方式进行装配；如果没有匹配，则回退为一个原始类型进行匹配，如果匹配则自动装配；
 
9：@PostConstruct，@PreDestroy
这两个注释只能应用于方法上，标注了@PostConstruct 注释的方法将在类实例化后调用，而标注了 @PreDestroy 的方法将在类销毁之前调用。
Java代码 

```java

@PostConstruct  
public void  init(){  
      System.out.println("I'm  init  method  using  @PostConstrut....");  
}  
@PreDestroy  
public void  dostory(){  
      System.out.println("I'm  destory method  using  @PreDestroy.....");  
}  

```