zoukankan      html  css  js  c++  java
  • Spring的注解@Qualifier小结

    有以下接口:

    public interface EmployeeService {
        public EmployeeDto getEmployeeById(Long id);
    }

    有两个实现类:

    @Service("service")
    public class EmployeeServiceImpl implements EmployeeService {
        public EmployeeDto getEmployeeById(Long id) {
            return new EmployeeDto();
        }
    }
    @Service("service1")
    public class EmployeeServiceImpl implements EmployeeService {
        public EmployeeDto getEmployeeById(Long id) {
            return new EmployeeDto();
        }
    }

    调用方法为:

    @Controller
    @RequestMapping("/emplayee")
    public class EmployeeInfoControl {
       
        @Autowired
        EmployeeService employeeService;
         
        @RequestMapping(params = "method=showEmplayeeInfo")
        public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) {
            #略
        }
    }

    报错

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeInfoControl': 
    Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: com.test.service.EmployeeService com.test.controller.EmployeeInfoControl.employeeService;
    nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
    No unique bean of type [com.test.service.EmployeeService] is defined: expected single matching bean but found 2: [service1, service2]

    很明显了,在autoware时,由于有两个类实现了EmployeeService接口,所以Spring不知道应该绑定哪个实现类,所以抛出了如上错误。

    这个时候就要用到@Qualifier注解了,qualifier的意思是合格者。通过这个标示,表明了哪个实现类才是我们所需要的,我们修改调用代码,添加@Qualifier注解,需要注意的是@Qualifier的参数名称必须为我们之前定义@Service注解的名称之一。

    @Controller
    @RequestMapping("/emplayee")
    public class EmployeeInfoControl {
        
        @Autowired
        @Qualifier("service")
        EmployeeService employeeService;
        
        @RequestMapping(params = "method=showEmplayeeInfo")
        public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) {
            #略
        }
    }
  • 相关阅读:
    数据库一直显示恢复中。。记录一则处理数据库异常的解决方法
    MSSQl分布式查询
    ASP.NET MVC中实现数据库填充的下拉列表 .
    理解浮点数的储存规则
    获取 "斐波那契数列" 的函数
    Int64 与 Currency
    学 Win32 汇编[33] 探讨 Win32 汇编的模块化编程
    学 Win32 汇编[34] 宏汇编(1)
    Delphi 中 "位" 的使用(2) 集合
    如何用弹出窗口显示进度 回复 "嘿嘿嘿" 的问题
  • 原文地址:https://www.cnblogs.com/ydymz/p/8464424.html
Copyright © 2011-2022 走看看