最近项目遇到了一个问题,Spring一个接口怎么多实现?方法有很多,总结了下,有两种方法:
1. @Primary注解指定一个主的实现,使用@Autowired就能实现自动注入
需要实现的接口
public interface HelloService {
public BizPo sayHi(String id);
}
接口实现1
@Service
@Primary
public class HelloHangZhouServiceImpl implements HelloService {
@Override
public BizPo sayHi(String id) {
System.out.println(list);
if (id.equals("1")) {
System.out.println("数据源1");
} else if (id.equals("2")) {
System.out.println("数据源2");
}
System.out.println("默认数据源");
return new BizPo(id,"hangzhou");
}
}
接口实现2
@Service
public class HelloGuangZhouServiceImpl implements HelloService {
@Override
public BizPo sayHi(String id) {
return new BizPo(id,"guangzhou");
}
}
Controller层
@RestController
public class HelloController {
//这里会自动注入加了@Primary注解的那个接口实现类
@Autowired
private HelloService helloService;
//自动注入实现了HelloService接口的实现类
@Autowired
private List<HelloService> list;
@GetMapping("/{id}")
public @ResponseBody BizPo getById(@PathVariable String id){
System.out.println("id ==> "+id);
BizPo b = helloService.sayHi(id);
System.out.println(b);
return b;
}
}
想要拿到所有的接口实现类怎么办?可以通过下面这个方式。
@Autowired
private List<HelloService> list;
那么如果我想拿到某个指定的bean怎么办?看方法2
2. @Service(“XXXX”)命名实现的名称+@Qualifier(“helloGuangZhouService”)&&@Resource指定需要注入的bean。
接口
public interface HelloService {
public BizPo sayHi(String id);
}
实现1
@Service("helloGuangZhouService")
public class HelloGuangZhouServiceImpl implements HelloService {
@Override
public BizPo sayHi(String id) {
return new BizPo(id,"guangzhou");
}
}
实现2
@Service("helloHangZhouService")
public class HelloHangZhouServiceImpl implements HelloService {
@Override
public BizPo sayHi(String id) {
System.out.println(list);
if (id.equals("1")) {
System.out.println("数据源1");
} else if (id.equals("2")) {
System.out.println("数据源2");
}
System.out.println("默认数据源");
return new BizPo(id,"hangzhou");
}
}
controller
@RestController
public class HelloController {
@Qualifier("helloGuangZhouService")
@Resource
private HelloService guangzhouservice;
@Qualifier("helloHangZhouService")
@Resource
private HelloService hangzhouservice;
@GetMapping("/{id}")
public @ResponseBody BizPo getById(@PathVariable String id){
System.out.println("id ==> "+id);
BizPo b = guangzhouservice.sayHi(id);
System.out.println(b);
return b;
}
}