@Qualifier的作用是什么

2021/6/22 22:16:24
栏目: 其他类
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

@Qualifier的作用是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

@Qualifier的作用

这是官方的介绍

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.

简单的理解就是:

  • 在使用@Autowire自动注入的时候,加上@Qualifier(“test”)可以指定注入哪个对象;

  • 可以作为筛选的限定符,我们在做自定义注解时可以在其定义上增加@Qualifier,用来筛选需要的对象。这个理解看下面的代码吧,不好解释。

功能介绍

首先是对(1)的理解。

//我们定义了两个TestClass对象,分别是testClass1和testClass2//我们如果在另外一个对象中直接使用@Autowire去注入的话,spring肯定不知道使用哪个对象//会排除异常 required a single bean, but 2 were found@Configurationpublic class TestConfiguration {   @Bean("testClass1")   TestClass testClass1(){       return new TestClass("TestClass1");
   }   @Bean("testClass2")
   TestClass testClass2(){       return new TestClass("TestClass2");
   }
}

下面是正常的引用

@RestControllerpublic class TestController {//此时这两个注解的连用就类似 @Resource(name="testClass1")@Autowired@Qualifier("testClass1")    private TestClass testClass;@GetMapping("/test")    public Object test(){return testClassList;
    }

}

@Autowired和@Qualifier这两个注解的连用在这个位置就类似 @Resource(name=“testClass1”)

对(2)的理解

@Configurationpublic class TestConfiguration {//我们调整下在testClass1上增加@Qualifier注解@Qualifier@Bean("testClass1")    TestClass testClass1(){return new TestClass("TestClass1");
    }

    @Bean("testClass2")TestClass testClass2(){return new TestClass("TestClass2");
    }
}
@RestControllerpublic class TestController {//我们这里使用一个list去接收testClass的对象@AutowiredList<TestClass> testClassList= Collections.emptyList();    @GetMapping("/test")public Object test(){return testClassList;
    }
}

我们调用得到的结果是

[
     {"name": "TestClass1" },
    {       "name": "TestClass2"}
]

我们可以看到所有的testclass都获取到了。接下来我们修改下代码

@RestControllerpublic class TestController {@Qualifier //我们在这增加注解@AutowiredList<TestClass> testClassList= Collections.emptyList();@GetMapping("/test")
    public Object test(){return testClassList;
    }
}

和上面代码对比就是在接收参数上增加了@Qualifier注解,这样看是有什么区别,我们调用下,结果如下:

[
     {"name": "TestClass1" }
]

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注辰讯云资讯频道,感谢您对辰讯云的支持。


辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: word如何批量把数字变下标