美文网首页架构
Springboot中一个service接口多个实现类,如何注入

Springboot中一个service接口多个实现类,如何注入

作者: 一个骚骚的码农 | 来源:发表于2021-09-06 14:05 被阅读0次

背景

有一个接口PersonService,然后再写两个实现类PersonServiceImp1、PersonServiceImp2

现状

如果我们直接注入接口的话,idea就会给我们报错

解决办法

其实自动注入时,它首先会先根据class类型来找到相应的实现类,如果这里有两个相同类型的实现类时,
1.那我们可以通过实现类的id来找,比如说PersonServiceImp1可以通过【personServiceImp1】这个id来找
2.除此之外还可以通过注解@Qualifier

    @Qualifier("propertyServiceImpl")
    @Autowired
    PropertyService propertyService;

3.我们也可以通过@Resource来代替@Autowired,通过我们指定我们指定的名字进行注入,首先要先在实现类上指定名字

@Service("Impl1")
public class PropertyServiceImpl1 implements PropertyService {
}

然后我们在注入的时候用@Resource来代替@Autowired

@Resource(name="Impl1")
PropertyService propertyService;

相关文章

网友评论

    本文标题:Springboot中一个service接口多个实现类,如何注入

    本文链接:https://www.haomeiwen.com/subject/jmbewltx.html