Spring中如何使用Qualifier注解

发布时间:2021-07-12 10:03:42 作者:Leah
来源:亿速云 阅读:113

Spring中如何使用Qualifier注解,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

一 配置

<?xml version="1.0" encoding="GBK"?><beans xmlns="http://www.springframework.org/schema/beans"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:context="http://www.springframework.org/schema/context"   xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd">   <context:component-scan base-package="org.crazyit.app.service"/>  </beans>

二 接口

Axe

package org.crazyit.app.service;public interface Axe{   public String chop();}

Person

package org.crazyit.app.service;public interface Person{   public void useAxe();}

三 Bean

Chinese

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.springframework.beans.factory.annotation.*;import org.crazyit.app.service.*;@Componentpublic class Chinese implements Person{  @Autowired  @Qualifier("steelAxe")  private Axe axe;//  // axe的setter方法//  @Autowired//  public void setAxe(@Qualifier("stoneAxe") Axe axe)//  {//    this.axe = axe;//  }  // 实现Person接口的useAxe()方法  public void useAxe()  {    // 调用axe的chop()方法,    // 表明Person对象依赖于axe对象    System.out.println(axe.chop());  }}

SteelAxe

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class SteelAxe implements Axe{  public String chop()  {    return "钢斧砍柴真快";  }}

StoneAxe

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class StoneAxe implements Axe{  public String chop()  {    return "石斧砍柴好慢";  }}

四 测试类

package lee;import org.springframework.context.*;import org.springframework.context.support.*;import org.crazyit.app.service.*;public class BeanTest{  public static void main(String[] args)  {    // 创建Spring容器    AbstractApplicationContext ctx = new      ClassPathXmlApplicationContext("beans.xml");    // 注册关闭钩子    ctx.registerShutdownHook();    Person person = ctx.getBean("chinese" , Person.class);    person.useAxe();  }}

五 测试结果

钢斧砍柴真快

关于Spring中如何使用Qualifier注解问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. Spring @Primary和@Qualifier注解的用法
  2. Spring实战之Qualifier注解用法示例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring qualifier

上一篇:Java中replace()函数如何使用

下一篇:.NET Core如何创建一个控制台程序

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》