欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

@Qualifier注解 Spring

程序员文章站 2022-05-24 14:38:30
...

@Qualifier注解一般与@Autowired注解配合使用
当一个实体类对应着多个实现类时

@Service
public class UserServiceImpl1 implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User checkUser(String username, String password) {

        return null;
    }
}
@Service
public class UserServiceImpl2 implements UserService {
    @Override
    public User checkUser(String username, String password) {
        return null;
    }
}

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

此时执行代码会发现如下报错

LoginController required a single bean, but 2 were found:
	- userService1: defined in file [E:\SoftWare\IntelliJ IDEA 2019.2.1\Project\myblog\target\classes\com\lxp\service\impl\UserServiceImpl.class]
	- userService2: defined in file [E:\SoftWare\IntelliJ IDEA 2019.2.1\Project\myblog\target\classes\com\lxp\service\impl\UserServiceImpl2.class]

找到了两个bean

这时候就用到了@Qualifier注解
将两个@service分别修改为

@Service("userService1")
@Service("userService2")

再对自动注入处添加@Qualifier注解

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    @Qualifier("userService1")
    private UserService userService;

就可以启动成功了

0-04-29 16:24:36.488  INFO 7444 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-04-29 16:24:36.547  INFO 7444 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-04-29 16:24:36.551  INFO 7444 --- [  restartedMain] com.lxp.MyblogApplication                : Started MyblogApplication in 5.981 seconds (JVM running for 8.099)
相关标签: spring java