在spring中出现,一个接口有两个实现类,怎么调用?
1接口
package com.example.demo.service;
public interface UserService {
void saveUser();
}
2实现类
实现类1
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service("userServiceImpl1")
public class UserServiceImpl implements UserService{
@Override
public void saveUser() {
System.out.println("测试实现1");
}
}
实现类2
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service("userServiceImpl2")
public class UserServiceImpl2 implements UserService{
@Override
public void saveUser() {
System.out.println("测试实现2");
}
}
3进行调用
controller层调用
使用@Autowired的注入方式进行注入,@Autowired的注入方式是byType注入,当要注入的类型在容器中存在多个时,Spring是不知道要要入哪个实现类,所以会报错。
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("save")
public String saveUser(){
userService.saveUser();
return "save ok";
}
}
启动直接报错,spring是单例的但是找到了两个实例。
3.1使用@Resource
使用**@Resource默认是按照byName的方式注入的**,如果通过byName的方式匹配不到,再按byType的方式匹配
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class UserController {
@Resource(name = "userServiceImpl1")
private UserService userService;
@RequestMapping("save")
public String saveUser(){
userService.saveUser();
return "save ok";
}
}
访问:http://localhost:8080/save
根据打印结果可以看到注入的是userServiceImpl1
更改为userServiceImpl2,打印的是测试实现2
3.2使用@Autowired和@Qualifier
@Qualifier注解也是byName的方式,是直接按照名字进行搜索,对于UserServiceImpl上面@Service注解必须写名字,不写就会报错,而且名字必须是@Autowired @Qualifie("userServiceImpl")保持一致。
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class UserController {
@Autowired
@Qualifier("userServiceImpl1")
private UserService userService;
@RequestMapping("save")
public String saveUser(){
userService.saveUser();
return "save ok";
}
}
浏览器访问:http://localhost:8080/save
可以看到用的是测试实现1