@Autowired 注释与@Qualifier 注释

来源:互联网 发布:大数据,银行风险 编辑:程序博客网 时间:2024/05/17 09:37
@Service("OrganDaoIbatis ")
public class OrganDaoIbatis extends BaseDao implements IOrganDao {
 @Autowired(required=false)
 @Qualifier("sqlMapClient")
 private SqlMapClient sqlClient = null;
 
 

使用 @Autowired(required = false)作用:

当候选 Bean 数目不为 1 时的应对方法

在默认情况下使用 @Autowired 注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean。

当然,一般情况下,使用 @Autowired 的地方都是需要注入 Bean 的,使用了自动注入而又允许不注入的情况一般仅会在开发期或测试期碰到(如为了快速启动 Spring 容器,仅引入一些模块的 Spring 配置文件),所以 @Autowired(required = false) 会很少用到。

 

@Qualifier 注释指定注入 Bean 的名称 作用:

和找不到一个类型匹配 Bean 相反的一个错误是:如果 Spring 容器中拥有多个候选 Bean,Spring 容器在启动时也会抛出 BeanCreationException 异常。

 

 

使用Autowired时你的OrganDaoIbatis 必须以@Service或@Component注解才行。 

0 0
原创粉丝点击