Spring IOC @Autowired、@Qualifier 、@Primary 注解说明

旧城等待, 2024-04-19 11:06 120阅读 0赞

#

1.@Autowired

依赖注入的注解

2.@Primary

官网文档的解释:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MzA2MDQx_size_16_color_FFFFFF_t_70

对应的翻译,来自搜狗(凑合可以看懂)

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MzA2MDQx_size_16_color_FFFFFF_t_70 1

代码示例:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MzA2MDQx_size_16_color_FFFFFF_t_70 2

个人理解:在通过javaconfig进行声明bean时,加上该注解后,那个bean时首要选择。

3.@Qualifier

标识符,因为@Autowired默认时按照bean的类型注入(bytype),当别注入的接口有多个实现时,如果不加以区分,程序将会出现异常,使用@Qualifier进行标识来解决这个问题

示例:

声明的bean

  1. package com.lhj.service;
  2. public interface UserService {
  3. void eat();
  4. }
  5. -------------------------------------------------------------
  6. package com.lhj.service.impl;
  7. import com.lhj.service.UserService;
  8. import org.springframework.beans.factory.annotation.Qualifier;
  9. import org.springframework.stereotype.Service;
  10. @Service
  11. public class UserServiceImpl implements UserService {
  12. public void eat() {
  13. System.out.println("UserServiceImpl");
  14. }
  15. }
  16. -------------------------------------------------------------
  17. package com.lhj.service.impl;
  18. import com.lhj.service.UserService;
  19. import org.springframework.stereotype.Service;
  20. @Service
  21. public class UserServiceExtendImpl implements UserService {
  22. public void eat() {
  23. System.out.println("UserServiceExtendImpl");
  24. }
  25. }

注入并使用bean

  1. package com.lhj.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.annotation.Qualifier;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class UserDemoService {
  7. @Autowired
  8. @Qualifier("userServiceExtendImpl")
  9. private UserService userService;
  10. }

添加@Qualifier来区分这里的UserServiceImpl 和UserServiceExtendImpl 两个bean ,@Qualifier括号内的值可以是bean的id或name值

官网文档说明:

20190917165301803.png

搜狗翻译

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MzA2MDQx_size_16_color_FFFFFF_t_70 3

发表评论

表情:
评论列表 (有 0 条评论,120人围观)

还没有评论,来说两句吧...

相关阅读

    相关 @Primary注解

    在看项目的时候看到了@Primary,因为之前没留意过,所以就去学习了一下,在此记录一下自己的理解,感叹一下还要学习的东西太多了,慢慢加油。 1.概述 @Pri

    相关 Spring中@Primary注解

    1.概述 讨论Spring的@Primary注解,该注解是框架在3.0版中引入的。 其作用与功能,当有多个相同类型的bean时,使用@Primary来赋予bean更高的